在HTML中嵌入JSON是否有标准? [英] Is there a standard for embedding JSON in HTML?

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

问题描述

我想在HTML中嵌入JSON。我找到的最优雅的解决方案使用脚本 -tag和mime媒体类型 application / json

 < script id =datatype =application / json> 
{
foo:bar
}
< / script>

这是嵌入JSON的标准方式吗?如果没有,上述解决方案是否存在风险?



使用内联JSON(而不是JSON-P服务)的原因:




  • 少量JSON数据

  • 少量HTTP请求

  • JSON转换为HTML属性中的数据



[更新] 嵌入json的原因。 b
$ b

我有一个流量非常高的网站的图库小部件。画廊可以包含100张或更多图片。我一次只显示一个图像,其余图像将被延迟加载。然而,所有图像的信息(图像src)将在页面加载时呈现在html中。有多种方法可以在html中呈现图像信息。而不是使用JSON,我也可以使用html数据属性,如下所示:

 < li class =imagedata-src = 图像path.jpg > 
<! - 图片标签将在这里使用javascript创建 - >
< / li>

会导致:

 < li class =image image-loadeddata-src =image-path.jpg> 
< img src =image-path.jpg/>
< / li>

上述解决方案的缺点是额外的标记。我宁愿使用JSON和Javascript-Templating引擎,例如 doT.js

解决方案


使用内联JSON(而不是JSON-P服务)的原因


您也可以内联JSON-P。好的,您只需调用该方法内联脚本,但它具有以下两个优点: - )


I would like to embed JSON in HTML. The most elegant solution I have found makes use of the script-tag and the mime media type application/json.

<script id="data" type="application/json">
    {
        "foo" : "bar"
    }
</script> 

Is this the standard way of embedding JSON? If not, are there any risks with the above solution?

Reasons for using inline JSON (instead of a JSON-P service):

  • Small amounts of JSON-data
  • Less HTTP-requests
  • Preference for inline-JSON to data in HTML-attributes

[UPDATE] Reason for embedding json.

I have a gallery widget for a website with very high traffic. The gallery can consist of a 100 images or more. I am only showing one image at a time and the rest of the images will be lazy loaded. However the information (image src) to all images will be rendered in the html on page load. There are various ways to render the image information in the html. Instead of using JSON I could also use html data attributes as shown below:

<li class="image" data-src="image-path.jpg">
    <!-- image tag will be created here using javascript -->
</li>

Will result in:

<li class="image image-loaded" data-src="image-path.jpg">
    <img src="image-path.jpg" />
</li>

The disadvantage with the above solution is the extra markup. I would rather use JSON and a Javascript-Templating engine such as doT.js.

解决方案

Reasons for using inline JSON (instead of a JSON-P service)

You can inline JSON-P as well. OK, you just call that method "inline script", but it has the advantages of both :-)

这篇关于在HTML中嵌入JSON是否有标准?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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