简体   繁体   English

将 JSON 对象存储在 HTML jQuery 中的数据属性中

[英]Store JSON object in data attribute in HTML jQuery

I am storing data using the data- approach in a HTML tag like so:我在 HTML 标签中使用data-方法存储数据,如下所示:

<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 .日志告诉我undefined So it seems like I can store simple strings in the data- attributes but I can't store JSON objects...所以看起来我可以在data-属性中存储简单的字符串,但我不能存储 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?关于如何使用data-方法在 HTML 标记中存储实际对象的任何想法?

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.好消息是 data- 属性中的字符串会自动转换为 JavaScript 对象。 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 中使用。

(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). (注意:为了让 data- 属性自动指定为 Object 而不是 String 类型,您必须小心编写有效的 JSON,尤其是将键名括在双引号中)。

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.data,则无论如何都将其抽象化。

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 Object]而不是直接 JSON,只需通过数据键访问您的 JSON:

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

This is how it worked for me.这就是它对我的工作方式。

Object目的

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

Set

Encode the stringified object with encodeURIComponent() and set as attribute:使用encodeURIComponent()对字符串化对象进行编码并设置为属性:

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

Get得到

To get the value as an object, parse the decoded, with decodeURIComponent() , attribute value:要获取作为对象的值,请使用decodeURIComponent()解析解码后的属性值:

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

A lot of problems with storing serialized data can be solved by converting theserialized string to base64 .通过将序列化字符串转换为base64可以解决存储序列化数据的许多问题。

A base64 string can be accepted just about anywhere with no fuss.几乎可以在任何地方接受 base64 字符串,而不必大惊小怪。

Take a look at:看一眼:

The WindowOrWorkerGlobalScope.btoa() method creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data. WindowOrWorkerGlobalScope.btoa()方法从 String 对象创建一个 base-64 编码的 ASCII 字符串,其中字符串中的每个字符都被视为一个二进制数据字节。

The WindowOrWorkerGlobalScope.atob() function decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.atob()函数对使用 base-64 编码的数据字符串进行解码

Convert to/from as needed.根据需要转换为/从。

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

Combine the use of window.btoa and window.atob together with JSON.stringify and JSON.parse .结合使用的window.btoawindow.atob连同JSON.stringifyJSON.parse

- This works for strings containing single quotes - 这适用于包含单引号的字符串

Encoding the data:编码数据:

var encodedObject = window.btoa(JSON.stringify(dataObject));

Decoding the data:解码数据:

var dataObject = JSON.parse(window.atob(encodedObject));

Here is an example of how the data is constructed and decoded later with the click event.这是稍后如何使用单击事件构造和解码数据的示例。

Construct the html and encode the data:构造html并对数据进行编码:

var encodedObject = window.btoa(JSON.stringify(dataObject));

"<td>" + "<a class='eventClass' href='#' data-topic='" + encodedObject + "'>" 
+ "Edit</a></td>"

Decode the data in the click event handler:解码单击事件处理程序中的数据:

$("#someElementID").on('click', 'eventClass', function(e) {
            event.preventDefault();
            var encodedObject = e.target.attributes["data-topic"].value;
            var dataObject = JSON.parse(window.atob(encodedObject));

            // use the dataObject["keyName"] 
}

There's a better way of storing JSON in the HTML:有一种在 HTML 中存储 JSON 的更好方法:

HTML HTML

<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>

JavaScript JavaScript

JSON.parse(document.getElementById('some-data').textContent);

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 properly 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.传入格式错误的 JSON 字符串会导致抛出 JavaScript 异常。 For example, the following are all invalid JSON strings:例如,以下都是无效的 JSON 字符串:

  1. "{test: 1}" ( test does not have double quotes around it). "{test: 1}"test周围没有双引号)。
  2. "{'test': 1}" ( 'test' is using single quotes instead of double quotes). "{'test': 1}"'test'使用单引号而不是双引号)。
  3. "'test'" ( 'test' is using single quotes instead of double quotes). "'test'"'test'使用单引号而不是双引号)。
  4. ".1" (a number must start with a digit; "0.1" would be valid). ".1" (数字必须以数字开头; "0.1"有效)。
  5. "undefined" ( undefined cannot be represented in a JSON string; null , however, can be). "undefined"undefined不能用 JSON 字符串表示;但是null可以)。
  6. "NaN" ( NaN cannot be represented in a JSON string; direct representation of Infinity is also n "NaN"NaN不能用 JSON 字符串表示;Infinity 的直接表示也是 n

Using the documented jquery .data(obj) syntax allows you to store an object on the DOM element.使用记录的 jquery .data(obj) 语法允许您在 DOM 元素上存储对象。 Inspecting the element will not show the data- attribute because there is no key specified for the value of the object.检查元素不会显示data-属性,因为没有为对象的值指定键。 However, data within the object can be referenced by key with .data("foo") or the entire object can be returned with .data() .但是,对象内的数据可以通过键使用.data("foo")来引用,或者可以使用.data()返回整个对象。

So assuming you set up a loop and result[i] = { name: "image_name" } :因此,假设您设置了一个循环并且result[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" }

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.作为替代方案,我最终将数据写入 dom 并在需要时将其解析回来。 Perhaps it's less efficient, but worked well for my purpose because I'm really prototyping data and not writing this for production.也许它的效率较低,但对我的目的很有效,因为我实际上是在对数据进行原型设计,而不是为生产而编写它。

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 中。

.data() works perfectly for most cases. .data()适用于大多数情况。 The only time I had a problem was when the JSON string itself had a single quote.我唯一遇到问题的时候是 JSON 字符串本身有一个单引号。 I could not find any easy way to get past this so resorted to this approach (am using Coldfusion as server language):我找不到任何简单的方法来解决这个问题,所以采用了这种方法(我使用 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>

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.它使您能够从数据标签中检索数组、推送新元素并将其以正确的 JSON 格式存储回数据标签中。 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);我发现$('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string);正确存储数组,但$('#my-data-div').data('namesarray', names_string); doesn't work.不起作用。

<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);
!DOCTYPE html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$("#btn1").click(function()
{
person = new Object();
person.name = "vishal";
person.age =20;
    $("div").data(person);
});
  $("#btn2").click(function()
{
    alert($("div").data("name"));
});

}); });

</script>
<body>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>
<div></div>
</body>


</html>

Anser:-Attach data to selected elements using an object with name/value pairs.
GET value using object propetis like name,age etc...

This code is working fine for me.这段代码对我来说很好用。

Encode data with btoa使用 btoa 编码数据

let data_str = btoa(JSON.stringify(jsonData));
$("#target_id").attr('data-json', data_str);

And then decode it with atob然后用atob解码

let tourData = $(this).data("json");
tourData = atob(tourData);

I found a better way in https://oblik.dev/utilities/config/ Basically what they do is have a parser from-to json-like objects without double quotes:我在https://oblik.dev/utilities/config/ 中找到了一个更好的方法,基本上他们所做的是有一个解析器 from-to json-like objects 没有双引号:

import { Parser } from 'oblik/utils/config'

let parser = new Parser()
let result = parser.parse('foo: bar, !baz')
console.log(result) // { foo: "bar", baz: false }

More examples:更多例子:

<div ob-foo="text: Hello, num: 42">My Foo component</div>

I would like to see something like this format standartized我想看到像这种格式标准化的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM