在 HTML 数据属性上添加 JSON 是不是很糟糕?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15838593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:14:09  来源:igfitidea点击:

Is it bad to add JSON on HTML data attribute?

javascripthtmljson

提问by Googlebot

Since HTML dataattribute allows adding any custom data, I wonder if it is a good idea to include a set of JSONlist as a dataattribute? Then, the corresponding JSONcan be easily accessed by JavaScriptevents with getAttribute("data-x").

由于 HTMLdata属性允许添加任何自定义数据,我想知道将一组JSON列表作为data属性包含在内是否是一个好主意?然后,相应的JSON可以通过JavaScript带有的事件轻松访问getAttribute("data-x")

In fact, my question is that: Is it standard, efficient, and reasonable to add a large set of data to an HTMLattribute?

事实上,我的问题是:将大量数据添加到HTML属性中是否标准、高效和合理?

For example

例如

<div data-x="A LARGE SET OF JSON DATA" id="x">

Or a large set of JSON data must be stored within <script>tag, and an HTMLattribute is not a right place for a large set of data, even for dataattribute.

或者大量的 JSON 数据必须存储在<script>标签中,并且一个HTML属性不是一个适合大量数据的地方,即使对于data属性也是如此。

回答by BentOnCoding

Instead of storing everything in the data attribute you could use an identifier to access the data.

您可以使用标识符来访问数据,而不是将所有内容都存储在数据属性中。

So for example you could do this :

例如,您可以这样做:

var myBigJsonObj = { 
                      data1 : { //lots of data}, 
                      data2 : { //lots of data}                   

                   };

and then you had some html like so :

然后你有一些像这样的html:

<div data-dataId="data1" id="x">

You can use jquery to get the data now like so :

您现在可以使用 jquery 获取数据,如下所示:

var dataId = $('#x').attr('data-dataId');

var myData = myBigJsonObj[dataId];

This is the best approach imho.

这是最好的方法恕我直言。

回答by Athman

Say you want to save the object var dataObj = { foo: 'something', bar: 'something else' };to an html data attribute.

假设您要将对象保存var dataObj = { foo: 'something', bar: 'something else' };到 html 数据属性。

Consider first stringifying the object such that we have var stringifiedDataObj = JSON.stringify(dataObj);

考虑首先对对象进行字符串化,使得我们有 var stringifiedDataObj = JSON.stringify(dataObj);

Then you can use jQuery to set the stringifiedDataObj as the data attribute e.g. with the jQuery.data()API

然后您可以使用 jQuery 将 stringifiedDataObj 设置为数据属性,例如使用jQuery.data()API

回答by Nick F

While there's nothing to stop you embedding a long string of JSON in a data attribute, arguably the more "correct" way of doing it would be to add one data attribute per property of the JSON data. eg:

虽然没有什么可以阻止您在数据属性中嵌入一长串 JSON,但可以说更“正确”的方法是为 JSON 数据的每个属性添加一个数据属性。例如:

Javascript:

Javascript:

var dataObj = { foo: 'something', bar: 'something else' }

HTML:

HTML:

<div data-foo="something" data-bar="something else"></div>

This way each piece of data in the JSON object corresponds to a separate, independently-accessible piece of data attached to the DOM element.

这样,JSON 对象中的每条数据都对应于附加到 DOM 元素的单独的、可独立访问的数据。

Bear in mind that either way you'll need to escape the values you're inserting into the HTML - otherwise stray " characters will break your page.

请记住,无论哪种方式,您都需要对插入 HTML 的值进行转义 - 否则杂散的 " 字符会破坏您的页面。

回答by Borz Alexandru

You could make use of Map. Where your element will be the key, and the value at that key could be an object in which you store wanted data. Something like this (not tested though):

您可以使用Map。您的元素将是键,该键的值可以是您存储所需数据的对象。像这样的东西(虽然没有测试):

(function(global) {

  const map = new Map();

  global.CustomData = {
    add(element, key, data) {
      if (!map.has(element)) {
        map.set(element, {});
      }

      map.get(element)[key] = data;

      return map.get(element);
    },

    get(element, key) {
      if (!map.has(element)) {
        return null;
      }

      if (key !== undefined) {
        return map.get(element)[key];
      }

      return map.get(element)
    },

    remove(element, key) {
      if (!map.has(element)) {
        return false;
      }

      delete map.get(element)[key];

      if (Object.keys(map.get(element)).length === 0) {
        map.delete(element);
      }

      return true;
    },

    clear(element) {

      if (!map.has(element)) {
        return false;
      }

      map.delete(element);

      return true;
    }
  }

})(window);

回答by Arcanox

Technically you can, and I have seen several sites do this, but another solution is to store your JSON in a <script>tag and put a reference to the script tag in the dataattribute. This is a better solution than just storing the data as a JS object in an actual script if the data is rendered to the page server-side, but there are CSP restrictions on inline script tags, for example.

从技术上讲,你可以,而且我已经看到几个站点这样做,但另一种解决方案是将你的 JSON 存储在一个<script>标签中,并在data属性中放置一个对脚本标签的引用。如果将数据呈现到页面服务器端,这比仅将数据作为 JS 对象存储在实际脚本中是更好的解决方案,但例如,对内联脚本标记存在 CSP 限制。

HTML

HTML

<div data-data-id="#MyScriptData" id="x"></div>

<script type="application/json" id="MyScriptData">
{
    "fruit": "apple",
    ...
}
</script>

JS

JS

$(function () {
    var dataId = $("#x").data("data-id");
    var dataTag = $(dataId);
    var dataJson = dataTag.html(); // returns a string containing the JSON data
    var data = JSON.parse(dataJson);

    ...
});