jQuery的数据属性不解析JSON字符串 [英] jquery data attribute not parsing json string

查看:80
本文介绍了jQuery的数据属性不解析JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON.stringify()将javascript对象数组保存在html数据属性中.当我尝试使用jquery .data()函数检索数据时,我没有得到反序列化的javascript对象数组,但是给了我纯正的json字符串.我阅读了,jQuery .data()函数将文档中引用的Json字符串反序列化

I am saving array of javascript objects in the html data attribute using JSON.stringify(). When I try to retrieve the data using jquery .data() function, I do not get deserialized array of javascript objects back, but gives me plain json string. I read, jquery .data() function deserializes Json string as quoted in documentation

当data属性是一个对象(以'{'开头)或数组(以'['开头)时,则使用jQuery.parseJSON来解析该字符串; 它必须遵循有效的JSON语法,包括带引号的属性名称.如果 该值不可解析为JavaScript值,而是保留为 字符串

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对象.

I think, mine is a valid json string, because, if I try $.parseJSON on that, it gives me back array of javascript objects.

请帮助!

推荐答案

您无需对对象进行字符串化即可使用jQuery.data()存储它们.像这样存储对象:

You don't need to stringify objects to store them using jQuery.data(). Just store the object like so:

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会在渲染时解析(作为对象)硬编码的数据属性,但是之后设置为字符串的任何数据属性,无论是否用花括号括起来,都将存储为文本.

jQuery will parse (as objects) hard coded data attributes at rendering time, but any data attribute you set as string afterwards, will be stored as text no matter if wrapped in curly braces or not.

这篇关于jQuery的数据属性不解析JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆