我正在考虑像这样在 DOM 中嵌入任意 JSON:
<script type="application/json" id="stuff">
{
"unicorns": "awesome",
"abc": [1, 2, 3]
}
</script>
这类似于将任意 HTML 模板存储在 DOM 中以供以后与 JavaScript 模板引擎一起使用的方式。在这种情况下,我们可以稍后检索 JSON 并解析它:
var stuff = JSON.parse(document.getElementById('stuff').innerHTML);
This works ,但这是最好的方法吗?这是否违反任何最佳实践或标准?
注意:我不是在寻找将 JSON 存储在 DOM 中的替代方法,我已经确定这是解决我遇到的特定问题的最佳解决方案。我只是在寻找最好的方法。
最佳答案
我认为你原来的方法是最好的。 HTML5 规范甚至解决了这种用途:
"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."
在此处阅读:http://dev.w3.org/html5/spec/Overview.html#the-script-element
你确实做到了。什么是不爱?无需对属性数据进行字符编码。您可以根据需要对其进行格式化。它具有表现力,预期用途很明确。感觉不像是 hack(例如,使用 CSS 来隐藏你的“载体”元素)。这是完全有效的。
https://stackoverflow.com/questions/9320427/