我使用 JSON.stringify()
在 html 数据属性中保存 JavaScript 对象数组。当我尝试使用 jquery .data()
函数检索数据时,我没有得到反序列化的 javascript 对象数组,而是得到了纯 json 字符串。我读到,jquery .data()
函数反序列化 Json 字符串,如文档中引用的
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string
我认为,我的是一个有效的 json 字符串,因为,如果我尝试 $.parseJSON
,它会返回 javascript 对象数组。
请帮忙!
最佳答案
您不需要使用 jQuery.data() 对对象进行字符串化来存储它们。只需像这样存储对象即可:
var myobject = { "name":"john", "age":30};
jQuery('#dataholder').data('theobject',myobject);
console.log(jQuery('#dataholder').data('theobject'));
console.log(jQuery('#data_attribute_method').data('theobject'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dataholder"></div>
<div id="data_attribute_method" data-theobject='{ "name":"jim", "age":31}'></div>
jQuery 将在渲染时解析(作为对象)硬编码的数据属性,但随后设置为字符串的任何数据属性都将存储为文本,无论是否用大括号括起来。
关于javascript - jquery数据属性不解析json字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864079/