在HTML jQuery的data属性中存储JSON对象

时间:2021-12-21 16:53:07

I am storing data using the data- approach in a HTML tag like so:

我正在用一个HTML标签中的数据方法来存储数据:

<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>

I am then retrieving the data in a callback like this:

然后我在回调中检索数据,如下所示:

$(this).data('imagename');

That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:

工作的很好。我被困住的是试图保存对象而不是它的一个属性。我试着这样做:

<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>

Then I tried to access the name property like this:

然后我试着访问name属性如下:

var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);

The log tells me undefined. So it seems like I can store simple strings in the data- attributes but I can't store JSON objects...

log表示未定义。看起来我可以在数据属性中存储简单的字符串,但是我不能存储JSON对象……

I've also tried to use this kid of syntax with no luck:

我还试着用这个不太走运的语法:

<div data-foobar='{"foo":"bar"}'></div>

Any idea on how to store an actual object in the HTML tag using the data- approach?

关于如何使用数据方法在HTML标记中存储实际对象,您有什么想法吗?

10 个解决方案

#1


108  

instead of embedding it in the text just use $('#myElement').data('key',jsonObject);

与其在文本中嵌入它,不如使用$('#myElement').data('key',jsonObject);

it won't actually be stored in the html, but if you're using jquery.data, all that is abstracted anyway.

它实际上不会存储在html中,但是如果您使用jquery的话。数据,所有这些都被抽象出来了。

To get the JSON back don't parse it, just call:

要取回JSON,不要解析它,只需调用:

var getBackMyJSON = $('#myElement').data('key');

If you are getting [Object Object] instead of direct JSON, just access your JSON by the data key:

如果您获取的是[Object]而不是直接的JSON,只需通过数据键访问JSON:

var getBackMyJSON = $('#myElement').data('key').key;

#2


116  

Actually, your last example:

实际上,你的最后一个例子:

<div data-foobar='{"foo":"bar"}'></div>

seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).

看起来运行良好(参见http://jsfiddle.net/GlauberRocha/Q6kKU/)。

The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don't see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.

数据属性中的字符串自动转换为JavaScript对象,这是件好事。相反,我认为这种方法没有任何缺点!一个属性足以存储一组数据,可以通过对象属性在JavaScript中使用。

(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).

(注意:对于要自动赋予类型对象而不是字符串的数据属性,必须小心编写有效的JSON,特别是要将键名括在双引号中)。

#3


11  

For me it work like that, as I need to store it in template...

对我来说,它是这样工作的,因为我需要将它存储在模板中……

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

#4


8  

This is how it worked for me.

这就是我的工作方式。

To save a JSON in HTML data attribute, Stringy JSON object and encode it with "encodeURIComponent()" method.

要在HTML数据属性中保存JSON,请使用Stringy JSON对象并使用“encodeURIComponent()”方法对其进行编码。

While reading the data back, decode it with "decodeURIComponent()" method and parse the string to JSON object.

在读取数据时,使用“decodeURIComponent()”方法对其进行解码,并将字符串解析为JSON对象。

Example:

例子:

var my_object ={"Super Hero":["Iron Man", "Super Man"]};

Saving Data:

保存数据:

var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);

Reading Data:

读取数据:

var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));

#5


4  

A lot of problems with storing serialized data can be solved by converting the serialized string to base64. A base64 string can be accepted just about anywhere with no fuss. Take a look at:

通过将序列化字符串转换为base64,可以解决存储序列化数据的许多问题。base64字符串几乎可以在任何地方被接受,没有任何麻烦。看一看:

atob()
btoa()

Convert to/from as needed.

根据需要转换到/从。

#6


1  

The trick for me was to add double quotes around keys and values. If you use a php function like json_encode will give you a json encoded string and an idea how to propery encode yours.

我的诀窍是在键和值周围添加双引号。如果您使用像json_encode这样的php函数,将为您提供json编码的字符串,并了解如何正确地对您的字符串进行编码。

jQuery('#elm-id').data('datakey') will return an object of the string, if the string is properly encoded as json.

如果字符串被正确编码为json,那么jQuery('#elm-id').data('datakey')将返回字符串的一个对象。

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

根据jQuery文档:(http://api.jquery.com/jquery.parsejson/)

Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

传入异常的JSON字符串将导致抛出一个JavaScript异常。例如,以下都是无效的JSON字符串:

  1. "{test: 1}" (test does not have double quotes around it).
  2. “{test: 1}”(test周围没有双引号)。
  3. "{'test': 1}" ('test' is using single quotes instead of double quotes).
  4. "{'test': 1}" ('test'是用单引号代替双引号)。
  5. "'test'" ('test' is using single quotes instead of double quotes).
  6. “test”(“test”是用单引号而不是双引号)。
  7. ".1" (a number must start with a digit; "0.1" would be valid).
  8. ”。1”(数字必须以数字开头;“0.1”将有效)。
  9. "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
  10. “undefined”(undefined)(在JSON字符串中无法表示undefined);然而,null)。
  11. "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n
  12. “NaN”(NaN不能用JSON字符串表示;无穷直接表示也是n

#7


0  

Using the documented jquery .data(obj) syntax allows you to store an object on the DOM element. Inspecting the element will not show the data- attribute because there is no key specified for the value of the object. However, data within the object can be referenced by key with .data("foo") or the entire object can be returned with .data().

使用文档化的jquery .data(obj)语法可以在DOM元素上存储对象。检查元素不会显示data-属性,因为没有为对象的值指定键。但是,可以使用.data(“foo”)键引用对象中的数据,也可以使用.data()返回整个对象。

So assuming you set up a loop and result[i] = { name: "image_name" } :

假设你建立了一个循环,结果[i] = {name: "image_name"}:

$('.delete')[i].data(results[i]); // => <button class="delete">Delete</delete>
$('.delete')[i].data('name'); // => "image_name"
$('.delete')[i].data(); // => { name: "image_name" }

#8


0  

For some reason, the accepted answer worked for me only if being used once on the page, but in my case I was trying to save data on many elements on the page and the data was somehow lost on all except the first element.

由于某些原因,只有在页面上使用一次时,才会使用已接受的答案,但在我的情况下,我试图在页面上的许多元素上保存数据,除了第一个元素之外,所有的数据都以某种方式丢失。

As an alternative, I ended up writing the data out to the dom and parsing it back in when needed. Perhaps it's less efficient, but worked well for my purpose because I'm really prototyping data and not writing this for production.

作为另一种选择,我最终将数据写入dom,并在需要时进行解析。也许它效率较低,但对我的目的来说,它工作得很好,因为我实际上是在原型化数据,而不是编写用于生产的数据。

To save the data I used:

保存我所使用的资料:

$('#myElement').attr('data-key', JSON.stringify(jsonObject));

To then read the data back is the same as the accepted answer, namely:

然后将数据读回来,与所接受的答案相同,即:

var getBackMyJSON = $('#myElement').data('key');

Doing it this way also made the data appear in the dom if I were to inspect the element with Chrome's debugger.

如果我要用Chrome的调试器来检查元素,这样做也会使数据出现在dom中。

#9


0  

.data() works perfectly for most cases. The only time I had a problem was when the JSON string itself had a single quote. I could not find any easy way to get past this so resorted to this approach (am using Coldfusion as server language):

.data()在大多数情况下都能很好地工作。我唯一的问题是当JSON字符串本身有一个引号时。我找不到任何简单的方法来解决这个问题,所以采用了这种方法(使用Coldfusion作为服务器语言):

    <!DOCTYPE html>
        <html>
            <head>
                <title>
                    Special Chars in Data Attribute
                </title>
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
                <script>
                    $(function(){
                        var o = $("##xxx");
                        /**
                            1. get the data attribute as a string using attr()
                            2. unescape
                            3. convert unescaped string back to object
                            4. set the original data attribute to future calls get it as JSON.
                        */
                        o.data("xxx",jQuery.parseJSON(unescape(o.attr("data-xxx"))));
                        console.log(o.data("xxx")); // this is JSON object.
                    });
                </script>
                <title>
                    Title of the document
                </title>
            </head>
            <body>
                <cfset str = {name:"o'reilly's stuff",code:1}>
<!-- urlencode is a CF function to UTF8 the string, serializeJSON converts object to strin -->
                <div id="xxx" data-xxx='#urlencodedformat(serializejson(str))#'>
                </div>
            </body>
        </html>

#10


0  

For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string); doesn't work.

为了记录,我发现以下代码是有效的。它使您能够从数据标记中检索数组,推入一个新元素,并以正确的JSON格式将其存储回数据标记中。因此,如果需要,可以再次使用相同的代码向数组中添加更多元素。我发现美元(“# my-data-div”)。attr(data-namesarray,names_string);正确地存储数组,但是$('#my-data-div')。数据(namesarray,names_string);是行不通的。

<div id="my-data-div" data-namesarray='[]'></div>

var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);

#1


108  

instead of embedding it in the text just use $('#myElement').data('key',jsonObject);

与其在文本中嵌入它,不如使用$('#myElement').data('key',jsonObject);

it won't actually be stored in the html, but if you're using jquery.data, all that is abstracted anyway.

它实际上不会存储在html中,但是如果您使用jquery的话。数据,所有这些都被抽象出来了。

To get the JSON back don't parse it, just call:

要取回JSON,不要解析它,只需调用:

var getBackMyJSON = $('#myElement').data('key');

If you are getting [Object Object] instead of direct JSON, just access your JSON by the data key:

如果您获取的是[Object]而不是直接的JSON,只需通过数据键访问JSON:

var getBackMyJSON = $('#myElement').data('key').key;

#2


116  

Actually, your last example:

实际上,你的最后一个例子:

<div data-foobar='{"foo":"bar"}'></div>

seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).

看起来运行良好(参见http://jsfiddle.net/GlauberRocha/Q6kKU/)。

The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don't see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.

数据属性中的字符串自动转换为JavaScript对象,这是件好事。相反,我认为这种方法没有任何缺点!一个属性足以存储一组数据,可以通过对象属性在JavaScript中使用。

(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).

(注意:对于要自动赋予类型对象而不是字符串的数据属性,必须小心编写有效的JSON,特别是要将键名括在双引号中)。

#3


11  

For me it work like that, as I need to store it in template...

对我来说,它是这样工作的,因为我需要将它存储在模板中……

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

#4


8  

This is how it worked for me.

这就是我的工作方式。

To save a JSON in HTML data attribute, Stringy JSON object and encode it with "encodeURIComponent()" method.

要在HTML数据属性中保存JSON,请使用Stringy JSON对象并使用“encodeURIComponent()”方法对其进行编码。

While reading the data back, decode it with "decodeURIComponent()" method and parse the string to JSON object.

在读取数据时,使用“decodeURIComponent()”方法对其进行解码,并将字符串解析为JSON对象。

Example:

例子:

var my_object ={"Super Hero":["Iron Man", "Super Man"]};

Saving Data:

保存数据:

var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);

Reading Data:

读取数据:

var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));

#5


4  

A lot of problems with storing serialized data can be solved by converting the serialized string to base64. A base64 string can be accepted just about anywhere with no fuss. Take a look at:

通过将序列化字符串转换为base64,可以解决存储序列化数据的许多问题。base64字符串几乎可以在任何地方被接受,没有任何麻烦。看一看:

atob()
btoa()

Convert to/from as needed.

根据需要转换到/从。

#6


1  

The trick for me was to add double quotes around keys and values. If you use a php function like json_encode will give you a json encoded string and an idea how to propery encode yours.

我的诀窍是在键和值周围添加双引号。如果您使用像json_encode这样的php函数,将为您提供json编码的字符串,并了解如何正确地对您的字符串进行编码。

jQuery('#elm-id').data('datakey') will return an object of the string, if the string is properly encoded as json.

如果字符串被正确编码为json,那么jQuery('#elm-id').data('datakey')将返回字符串的一个对象。

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

根据jQuery文档:(http://api.jquery.com/jquery.parsejson/)

Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

传入异常的JSON字符串将导致抛出一个JavaScript异常。例如,以下都是无效的JSON字符串:

  1. "{test: 1}" (test does not have double quotes around it).
  2. “{test: 1}”(test周围没有双引号)。
  3. "{'test': 1}" ('test' is using single quotes instead of double quotes).
  4. "{'test': 1}" ('test'是用单引号代替双引号)。
  5. "'test'" ('test' is using single quotes instead of double quotes).
  6. “test”(“test”是用单引号而不是双引号)。
  7. ".1" (a number must start with a digit; "0.1" would be valid).
  8. ”。1”(数字必须以数字开头;“0.1”将有效)。
  9. "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
  10. “undefined”(undefined)(在JSON字符串中无法表示undefined);然而,null)。
  11. "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n
  12. “NaN”(NaN不能用JSON字符串表示;无穷直接表示也是n

#7


0  

Using the documented jquery .data(obj) syntax allows you to store an object on the DOM element. Inspecting the element will not show the data- attribute because there is no key specified for the value of the object. However, data within the object can be referenced by key with .data("foo") or the entire object can be returned with .data().

使用文档化的jquery .data(obj)语法可以在DOM元素上存储对象。检查元素不会显示data-属性,因为没有为对象的值指定键。但是,可以使用.data(“foo”)键引用对象中的数据,也可以使用.data()返回整个对象。

So assuming you set up a loop and result[i] = { name: "image_name" } :

假设你建立了一个循环,结果[i] = {name: "image_name"}:

$('.delete')[i].data(results[i]); // => <button class="delete">Delete</delete>
$('.delete')[i].data('name'); // => "image_name"
$('.delete')[i].data(); // => { name: "image_name" }

#8


0  

For some reason, the accepted answer worked for me only if being used once on the page, but in my case I was trying to save data on many elements on the page and the data was somehow lost on all except the first element.

由于某些原因,只有在页面上使用一次时,才会使用已接受的答案,但在我的情况下,我试图在页面上的许多元素上保存数据,除了第一个元素之外,所有的数据都以某种方式丢失。

As an alternative, I ended up writing the data out to the dom and parsing it back in when needed. Perhaps it's less efficient, but worked well for my purpose because I'm really prototyping data and not writing this for production.

作为另一种选择,我最终将数据写入dom,并在需要时进行解析。也许它效率较低,但对我的目的来说,它工作得很好,因为我实际上是在原型化数据,而不是编写用于生产的数据。

To save the data I used:

保存我所使用的资料:

$('#myElement').attr('data-key', JSON.stringify(jsonObject));

To then read the data back is the same as the accepted answer, namely:

然后将数据读回来,与所接受的答案相同,即:

var getBackMyJSON = $('#myElement').data('key');

Doing it this way also made the data appear in the dom if I were to inspect the element with Chrome's debugger.

如果我要用Chrome的调试器来检查元素,这样做也会使数据出现在dom中。

#9


0  

.data() works perfectly for most cases. The only time I had a problem was when the JSON string itself had a single quote. I could not find any easy way to get past this so resorted to this approach (am using Coldfusion as server language):

.data()在大多数情况下都能很好地工作。我唯一的问题是当JSON字符串本身有一个引号时。我找不到任何简单的方法来解决这个问题,所以采用了这种方法(使用Coldfusion作为服务器语言):

    <!DOCTYPE html>
        <html>
            <head>
                <title>
                    Special Chars in Data Attribute
                </title>
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
                <script>
                    $(function(){
                        var o = $("##xxx");
                        /**
                            1. get the data attribute as a string using attr()
                            2. unescape
                            3. convert unescaped string back to object
                            4. set the original data attribute to future calls get it as JSON.
                        */
                        o.data("xxx",jQuery.parseJSON(unescape(o.attr("data-xxx"))));
                        console.log(o.data("xxx")); // this is JSON object.
                    });
                </script>
                <title>
                    Title of the document
                </title>
            </head>
            <body>
                <cfset str = {name:"o'reilly's stuff",code:1}>
<!-- urlencode is a CF function to UTF8 the string, serializeJSON converts object to strin -->
                <div id="xxx" data-xxx='#urlencodedformat(serializejson(str))#'>
                </div>
            </body>
        </html>

#10


0  

For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string); doesn't work.

为了记录,我发现以下代码是有效的。它使您能够从数据标记中检索数组,推入一个新元素,并以正确的JSON格式将其存储回数据标记中。因此,如果需要,可以再次使用相同的代码向数组中添加更多元素。我发现美元(“# my-data-div”)。attr(data-namesarray,names_string);正确地存储数组,但是$('#my-data-div')。数据(namesarray,names_string);是行不通的。

<div id="my-data-div" data-namesarray='[]'></div>

var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);