I'm trying these HTML
<div data-params="{a: 1, b: '2'}" id="TEST1"></div> <div data-params='{"a": 1, "b": "2"}' id="TEST2"></div>
Then I use data() method in the jQuery
$('#TEST1').data('params'); //return a string $('#TEST2').data('params'); //return a object
But TEST1 it's not a return object, but a string, it can only return object TEST2. But I want to get a object by TEST1, How do I do it?
=============
Finally, I choose to write a function to achieve their own needs
$.fn.data2 = function(key, value) { if (value === undefined) { var data = $(this).data(key); if (typeof(data) === 'string') { var _data = data.replace(/^[\s\r\n]*/g, '').replace(/[\s\r\n]*$/g, ''); if (_data.match(/\{.*\}/) || _data.match(/\[.*\]/)) { try { _data = (new Function( 'return ' + data ))(); if (typeof(_data) == 'object') { $(this).data(key, _data); data = _data; } } catch(ex) {} } } return data; } return $(this).data(key, value); };
The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})
We want to send the data of our HTML form directly to the JSON file. For this we are using json_encode() function which returns a JSON encoded string. We are making an array of values that the user fills in the HTML form. Then we pass this array into json_encode() function.
In order to be parsed as an object, the data attribute must be a well formed JSON object.
In your case you just need to quote the object keys (as you do in the second object). Try:
<div data-params='{"a": 1, "b": "2"}' id="TEST1"></div>
For more info see the data method docs, the relevant part is this one (emphasis mine):
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string... ...When the data attribute is an object (starts with
'{'
) or array (starts with'['
) thenjQuery.parseJSON
is used to parse the string; it must follow valid JSON syntax including quoted property names.
You can escape the inner quotes:
<div data-params="{"a": 1, "b": "2"}" id="TEST2"></div>
But there is nothing wrong with your second method:
<div data-params='{"a": 1, "b": "2"}' id="TEST2"></div>
I would use that.
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