在DOM中嵌入任意JSON的最佳做法? [英] Best practice for embedding arbitrary JSON in the DOM?

查看:171
本文介绍了在DOM中嵌入任意JSON的最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在DOM中嵌入任意的JSON,如下所示:

 < script type =application / json id =stuff> 
{
unicorns:awesome,
abc:[1,2,3]
}
< / script>

这与在DOM中存储任意HTML模板的方法类似,以备以后使用JavaScript模板引擎。在这种情况下,我们可以稍后检索JSON并解析:

  var stuff = JSON.parse(document.getElementById '东西')的innerHTML)。 

这样做是有用的,但它是最好的方法吗?这是否违反任何最佳做法或标准?



注意:我不是在寻找在DOM中存储JSON的替代方法,我已经决定我遇到的特殊问题的最佳解决方案。我只是寻找最好的方法。

解决方案

我认为你原来的方法是最好的。 HTML5规范甚至解决了这种用法:


当用于包含数据块(而不是脚本)时,数据
必须嵌入内联,数据格式必须使用
的type属性,不能指定src属性,脚本元素的
内容必须符合要求
为所使用的格式定义。


阅读这里: http://dev.w3.org/html5/spec/Overview.html#the-script-element



你已经做到了这一点。什么不爱?没有字符编码需要属性数据。如果需要,您可以格式化。它具有表现力,用途明确。它不像一个黑客(例如使用CSS来隐藏你的载体元素)。这是完全有效的。


I'm thinking about embedding arbitrary JSON in the DOM like this:

<script type="application/json" id="stuff">
    {
        "unicorns": "awesome",
        "abc": [1, 2, 3]
    }
</script>

This is similar to the way one might store an arbitrary HTML template in the DOM for later use with a JavaScript template engine. In this case, we could later retrieve the JSON and parse it with:

var stuff = JSON.parse(document.getElementById('stuff').innerHTML);

This works, but is it the best way? Does this violate any best practice or standard?

Note: I'm not looking for alternatives to storing JSON in the DOM, I've already decided that's the best solution for the particular problem I'm having. I'm just looking for the best way to do it.

解决方案

I think your original method is the best. The HTML5 spec even addresses this use:

"When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used."

Read here: http://dev.w3.org/html5/spec/Overview.html#the-script-element

You've done exactly that. What is not to love? No character encoding as needed with attribute data. You can format it if you want. It's expressive and the intended use is clear. It doesn't feel like a hack (e.g. as using CSS to hide your "carrier" element does). It's perfectly valid.

这篇关于在DOM中嵌入任意JSON的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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