Javascript JSON 和 JSONP 之间有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2887209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the differences between JSON and JSONP?
提问by Mohammad
Format wise, file type wise and practical use wise?
格式明智,文件类型明智和实际使用明智?
回答by Marius
JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:
JSONP 是带有填充的 JSON。也就是说,你在开头放了一个字符串,并在它周围放了一对括号。例如:
//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});
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:
结果是您可以将 JSON 作为脚本文件加载。如果您之前设置了一个名为 的函数func,那么在脚本文件加载完成后,将使用一个参数(即 JSON 数据)调用该函数。这通常用于允许使用 JSON 数据进行跨站点 AJAX。如果您知道 example.com 正在提供类似于上面给出的 JSONP 示例的 JSON 文件,那么您可以使用这样的代码来检索它,即使您不在 example.com 域中:
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);
回答by mpen
Basically, you're not allowed to request JSON data from another domain via AJAX due to same-origin policy. AJAX allows you to fetch data after a page has already loaded, and then execute some code/call a function once it returns. We can't use AJAX but we are allowed to inject <script>tags into our own page and those are allowed to reference scripts hosted at other domains.
基本上,由于同源策略,您不允许通过 AJAX 从另一个域请求 JSON 数据。AJAX 允许您在页面加载后获取数据,然后在返回后执行一些代码/调用函数。我们不能使用 AJAX,但我们可以将<script>标记注入我们自己的页面,并且这些标记可以引用托管在其他域的脚本。
Usually you would use this to include libraries from a CDN such as jQuery. However, we can abuse this and use it to fetch data instead! JSON is already valid JavaScript (for the most part), but we can't just return JSON in our script file, because we have no way of knowing when the script/data has finished loading and we have no way of accessing it unless it's assigned to a variable or passed to a function. So what we do instead is tell the web service to call a function on our behalf when it's ready.
通常,您会使用它来包含来自 CDN 的库,例如jQuery。但是,我们可以滥用它并使用它来获取数据!JSON 已经是有效的 JavaScript(在大多数情况下),但我们不能只在我们的脚本文件中返回 JSON,因为我们无法知道脚本/数据何时完成加载,我们也无法访问它,除非它是分配给变量或传递给函数。所以我们要做的是告诉 Web 服务在它准备好时代表我们调用一个函数。
For example, we might request some data from a stock exchange API, and along with our usual API parameters, we give it a callback, like ?callback=callThisWhenReady. The web service then wraps the data with our function and returns it like this: callThisWhenReady({...data...}). Now as soon as the script loads, your browser will try to execute it (as normal), which in turns calls our arbitrary function and feeds us the data we wanted.
例如,我们可能会从证券交易所 API 请求一些数据,并且连同我们常用的 API 参数,我们给它一个回调,例如?callback=callThisWhenReady. Web服务,然后包装我们的函数的数据并返回它是这样的:callThisWhenReady({...data...})。现在,只要脚本加载,您的浏览器就会尝试执行它(正常情况下),它依次调用我们的任意函数并向我们提供我们想要的数据。
It works much like a normal AJAX request except instead of calling an anonymous function, we have to use named functions.
它的工作方式与普通的 AJAX 请求非常相似,只是我们必须使用命名函数而不是调用匿名函数。
jQuery actually supports this seamlessly for you by creating a uniquely named function for you and passing that off, which will then in turn run the code you wanted.
实际上,jQuery 通过为您创建一个唯一命名的函数并将其传递给您,从而无缝地为您提供支持,然后该函数将依次运行您想要的代码。
回答by Alex Wayne
回答by Sankar
JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.
JSONP 代表“带填充的 JSON”,它是一种从不同域加载数据的解决方法。它将脚本加载到 DOM 的头部,因此您可以像在自己的域中加载信息一样访问信息,从而绕过跨域问题。
jsonCallback(
{
"sites":
[
{
"siteName": "JQUERY4U",
"domainName": "http://www.jquery4u.com",
"description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
},
{
"siteName": "BLOGOOLA",
"domainName": "http://www.blogoola.com",
"description": "Expose your blog to millions and increase your audience."
},
{
"siteName": "PHPSCRIPTS4U",
"domainName": "http://www.phpscripts4u.com",
"description": "The Blog of Enthusiastic PHP Scripters"
}
]
});
(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.
现在我们可以使用 JSONP 和我们围绕 JSON 内容创建的回调函数通过 AJAX 请求 JSON。输出应该是作为对象的 JSON,然后我们可以不受限制地将数据用于我们想要的任何内容。
回答by Delan Azabani
JSONP is essentially, JSON with extra code, like a function call wrapped around the data. It allows the data to be acted on during parsing.
JSONP 本质上是带有额外代码的 JSON,就像围绕数据的函数调用。它允许在解析期间对数据进行操作。
回答by Elangovan
JSON
JSON
JSON (JavaScript Object Notation)is a convenient way to transport data between applications, especially when the destination is a JavaScript application.
JSON(JavaScript Object Notation)是一种在应用程序之间传输数据的便捷方式,尤其是当目标是 JavaScript 应用程序时。
Example:
例子:
Here is a minimal example that uses JSON as the transport for the server response. The client makes an Ajax request with the jQuery shorthand function $.getJSON. The server generates a hash, formats it as JSON and returns this to the client. The client formats this and puts it in a page element.
这是一个使用 JSON 作为服务器响应传输的最小示例。客户端使用 jQuery 速记函数 $.getJSON 发出 Ajax 请求。服务器生成一个散列,将其格式化为 JSON 并将其返回给客户端。客户端对此进行格式化并将其放入页面元素中。
Server:
服务器:
get '/json' do
content_type :json
content = { :response => 'Sent via JSON',
:timestamp => Time.now,
:random => rand(10000) }
content.to_json
end
Client:
客户:
var url = host_prefix + '/json';
$.getJSON(url, function(json){
$("#json-response").html(JSON.stringify(json, null, 2));
});
Output:
输出:
{
"response": "Sent via JSON",
"timestamp": "2014-06-18 09:49:01 +0000",
"random": 6074
}
JSONP (JSON with Padding)
JSONP(带填充的 JSON)
JSONPis a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.
当从客户端发送来自不同域的 JSON 响应时,JSONP是一种克服浏览器限制的简单方法。
The only change on the client side with JSONP is to add a callback parameter to the URL
客户端对 JSONP 的唯一更改是向 URL 添加回调参数
Server:
服务器:
get '/jsonp' do
callback = params['callback']
content_type :js
content = { :response => 'Sent via JSONP',
:timestamp => Time.now,
:random => rand(10000) }
"#{callback}(#{content.to_json})"
end
Client:
客户:
var url = host_prefix + '/jsonp?callback=?';
$.getJSON(url, function(jsonp){
$("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
});
Output:
输出:
{
"response": "Sent via JSONP",
"timestamp": "2014-06-18 09:50:15 +0000",
"random": 364
}
Link:http://www.codingslover.blogspot.in/2014/11/what-are-differences-between-json-and-jsonp.html
链接:http : //www.codingslover.blogspot.in/2014/11/what-are-differences-between-json-and-jsonp.html
回答by Vasiliy Faronov
“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What's the fun in programming if everything just works?
“JSONP 是带有额外代码的 JSON”对于现实世界来说太容易了。不,你必须有一些差异。如果一切正常,编程有什么乐趣?
Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.
原来JSON 不是 JavaScript 的子集。如果你所做的只是获取一个 JSON 对象并将其包装在一个函数调用中,那么有一天你会被奇怪的语法错误所困扰,就像我今天一样。
回答by faridcs
JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.
当从客户端发送来自不同域的 JSON 响应时,JSONP 是一种克服浏览器限制的简单方法。
But the practical implementation of the approach involves subtle differences that are often not explained clearly.
但是,该方法的实际实施涉及通常无法清楚解释的细微差别。
Here is a simple tutorial that shows JSON and JSONP side by side.
这是一个并排显示 JSON 和 JSONP 的简单教程。
All the code is freely available at Github and a live version can be found at http://json-jsonp-tutorial.craic.com
所有代码都可以在 Github 上免费获得,并且可以在http://json-jsonp-tutorial.craic.com上找到实时版本

