Store and use an array using the HTML data tag and jQuery
If you use valid JSON ([
and ]
for the array, double quotes instead of single), like this:
<div id="locations" data-locations='[{"name":"Bath","url":"/location/bath","img":"/thumb.jpg"},{"name":"Berkhamsted","url":"/location/berkhamsted","img":"/thumb.jpg"}]'>
Then what you have (using .data()
) to get the array will work:
$('#locations').data('locations');
If for whatever reason you insist on using double quotes, you will need to html encode the quotes in your data attribute.
<div data-dwarfs="["Doc", "Sneezy", "Happy"]"></div>
Of course if you have access to PHP or some other pre-processor, you could use something like this:
<?php $dwarfs = ['Doc', 'Sneezy', 'Happy'];?> <div data-dwarfs="<?php echo htmlspecialchars(json_encode($dwarfs), ENT_QUOTES, 'UTF-8') ?>"></div><?php