JSON和JSONP有什么区别? [英] What are the differences between JSON and JSONP?

查看:105
本文介绍了JSON和JSONP有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

格式明智,文件类型明智和实用明智吗?

Format wise, file type wise and practical use wise?

推荐答案

JSONP是带填充的JSON,也就是说,你放了一开始的字符串和它周围的一对括号。例如:

JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

结果是您可以将JSON作为脚本文件加载。如果您之前设置了一个名为 func 的函数,那么当脚本文件加载完成后,将使用一个参数(即JSON数据)调用该函数。这通常用于允许带有JSON数据的跨站点AJAX。如果您知道example.com正在提供看起来像上面给出的JSONP示例的JSON文件,那么您可以使用这样的代码来检索它,即使您不在example.com域中:

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
  alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

这篇关于JSON和JSONP有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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