JSON 和 JSONP 有什么区别?

发布于 2024-09-02 04:13:32 字数 26 浏览 1 评论 0原文

格式明智、文件类型明智和实际用途明智?

Format wise, file type wise and practical use wise?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

鸵鸟症 2024-09-09 04:13:32

JSONP 是带填充的 JSON。也就是说,您在开头放置一个字符串,并在其周围放置一对括号。例如:

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

结果是您可以将 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);

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});

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);
甚是思念 2024-09-09 04:13:32

基本上,由于同源策略,您不允许通过 AJAX 从另一个域请求 JSON 数据。 AJAX 允许您在页面加载后获取数据,然后在返回后执行一些代码/调用函数。我们不能使用 AJAX,但我们可以将

通常您会使用它来包含来自 CDN 的库,例如 jQuery。但是,我们可以滥用它并用它来获取数据! JSON 已经是有效的 JavaScript(大部分),但我们不能只需在脚本文件中返回 JSON,因为我们无法知道脚本/数据何时完成加载,并且除非将其分配给变量或传递给函数,否则我们无法访问它。因此,我们所做的就是告诉 Web 服务在准备好时代表我们调用一个函数。

例如,我们可能会从股票交易 API 请求一些数据,除了我们常用的 API 参数之外,我们还会给它一个回调,例如 ?callback=callThisWhenReady。然后,Web 服务使用我们的函数包装数据并返回它,如下所示:callThisWhenReady({...data...})。现在,一旦脚本加载,您的浏览器就会尝试执行它(正常),这反过来又调用我们的任意函数并向我们提供我们想要的数据。

它的工作方式很像普通的 AJAX 请求,只不过我们必须使用命名函数而不是调用匿名函数。

实际上,jQuery 通过为您创建一个唯一命名的函数并将其传递出去,从而无缝地为您提供支持,然后该函数将依次运行您想要的代码。

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.

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.

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.

It works much like a normal AJAX request except instead of calling an anonymous function, we have to use named functions.

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.

海夕 2024-09-09 04:13:32

JSONP 允许您指定传递 JSON 对象的回调函数。这允许您绕过同源策略并将 JSON 从外部服务器加载到网页上的 JavaScript 中。

JSONP allows you to specify a callback function that is passed your JSON object. This allows you to bypass the same origin policy and load JSON from an external server into the JavaScript on your webpage.

格子衫的從容 2024-09-09 04:13:32

JSONP 代表“JSON with Padding”,它是从不同域加载数据的一种解决方法。它将脚本加载到 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);

现在我们可以使用 JSONP 和我们围绕 JSON 内容创建的回调函数通过 AJAX 请求 JSON。
输出应该是作为对象的 JSON,然后我们可以不受限制地将数据用于我们想要的任何用途。

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.

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.

黯然#的苍凉 2024-09-09 04:13:32

JSONP 本质上是带有额外代码的 JSON,就像围绕数据的函数调用。它允许在解析期间对数据进行操作。

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.

深空失忆 2024-09-09 04:13:32

JSON

JSON(JavaScript 对象表示法) 是一种在应用程序之间传输数据的便捷方式,尤其是当目标是 JavaScript 应用程序时。

示例:

这是一个使用 JSON 作为服务器响应传输的最小示例。客户端使用 jQuery 速记函数 $.getJSON 发出 Ajax 请求。服务器生成哈希值,将其格式化为 JSON 并将其返回给客户端。客户端对其进行格式化并将其放入页面元素中。

服务器:

get '/json' do
 content_type :json
 content = { :response  => 'Sent via JSON',
            :timestamp => Time.now,
            :random    => rand(10000) }
 content.to_json
end

客户端:

var url = host_prefix + '/json';
$.getJSON(url, function(json){
  $("#json-response").html(JSON.stringify(json, null, 2));
});

输出:

  {
   "response": "Sent via JSON",
   "timestamp": "2014-06-18 09:49:01 +0000",
   "random": 6074
  }

JSONP(带填充的 JSON)

JSONP 是一个从客户端发送来自不同域的 JSON 响应时克服浏览器限制的简单方法。

JSONP 客户端的唯一更改是向 URL 添加回调参数

服务器:

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

客户端:

var url = host_prefix + '/jsonp?callback=?';
$.getJSON(url, function(jsonp){
  $("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
});

输出:

 {
  "response": "Sent via JSONP",
  "timestamp": "2014-06-18 09:50:15 +0000",
  "random": 364
}

JSON

JSON (JavaScript Object Notation) is a convenient way to transport data between applications, especially when the destination is a JavaScript application.

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.

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 is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.

The only change on the client side with JSONP is to add a callback parameter to the 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
}
与君绝 2024-09-09 04:13:32

“JSONP 是带有额外代码的 JSON”对于现实世界来说太容易了。不,你必须有一点差异。如果一切都正常的话,编程还有什么乐趣呢?

事实证明 JSON 不是 JavaScript 的子集。如果您所做的只是获取一个 JSON 对象并将其包装在函数调用中,有一天您会遇到奇怪的语法错误,就像我今天一样。

“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?

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.

哽咽笑 2024-09-09 04:13:32

JSONP 是一种在客户端从不同域发送 JSON 响应时克服浏览器限制的简单方法。

但该方法的实际实施涉及微妙的差异,这些差异通常无法清楚地解释。

这是一个简单的教程,并排显示了 JSON 和 JSONP。

所有代码均可在 Github 上免费获取,实时版本可在 http://json-jsonp- 找到教程.craic.com

JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.

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.

All the code is freely available at Github and a live version can be found at http://json-jsonp-tutorial.craic.com

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文