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!
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")
The recommended way is to use HTML5 data-*
attributes:
<a href="#" id="myLnk" data-id="1" data-foo="bar" data-something="else">Click</a>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With