Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass lots of data from a single anchor tag

What is the best way to pass a lot of data from a single link? Is something like this a good idea or is there a better way?

<a href="{ 'id':'1', 'foo':'bar', 'something':'else' }" id="myLnk" > Click </a>


$('#myLnk).click( function(event){
  event.preventDeafult();
  var data = $(this).attr('href')
  console.log( $.parseJSON( response ) );

})

Thanks!

like image 710
Pardoner Avatar asked May 22 '11 00:05

Pardoner


3 Answers

The best way to do this is probably to use custom data attributes in your anchor tag.

For example:

<a href="#" data-json="{ 'id':'1', 'foo':'bar', 'something':'else' }">Click</a>

You can then easily access this data from your JavaScript using the jQuery data() function.

Or, rather than bundling all the data together in a single JSON block, you can split it into separate attributes:

<a id="myLnk"
    data-id="1"
    data-foo="bar"
    data-something="else">

These can then be retrieved using jQuery like this:

$("#myLnk").data("id")
$("#myLnk").data("foo")
$("#myLnk").data("something")
like image 158
Chris Fulstow Avatar answered Oct 28 '22 10:10

Chris Fulstow


The recommended way is to use HTML5 data-* attributes:

<a href="#" id="myLnk" data-id="1" data-foo="bar" data-something="else">Click</a>
like image 39
mVChr Avatar answered Oct 28 '22 08:10

mVChr


To add to Chris's & MvChr's responses, you can also do this, although I hate using single quotes for attributes:

<a href='#' data-json='{ "id":1, "foo":"bar", "something":"else" }'>Click</a>

The reason for this syntax is because if you quote it properly, $.data in jQuery will automatically work. Otherwise, you have to $.parseJSON($.data(selector)) the information.

like image 21
John Green Avatar answered Oct 28 '22 10:10

John Green