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

查看:35
本文介绍了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 parentheses 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天全站免登陆