有人能用外行人解释什么是JSONP吗? [英] Can anyone explain what JSONP is, in layman terms?

查看:69
本文介绍了有人能用外行人解释什么是JSONP吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JSONPJSON带填充.

我了解JSON是什么,以及如何与 jQuery.getJSON() 一起使用.但是,在引入JSONP时,我不理解callback的概念.

I understand what JSON is, and how to use it with jQuery.getJSON(). However, I do not understand the concept of the callback when introducing JSONP.

有人可以向我解释这是如何工作的吗?

Can anyone explain to me how this works?

推荐答案

前言:

此答案已有6年以上的历史了.虽然JSONP的概念和应用没有改变 (即答案的详细信息仍然有效),您应该 希望在可能的情况下使用CORS (即您的服务器 API 支持它,并且 浏览器支持就足够了), 由于JSONP 具有固有的安全风险.

Preface:

This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.

JSONP(带有填充的JSON )是一种常用的方法 绕过Web浏览器中的跨域策略. (不允许您向浏览器认为在其他服务器上的网页发出AJAX请求.)

JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)

JSON和JSONP在客户端和服务器上的行为不同.不会使用XMLHTTPRequest和关联的浏览器方法调度JSONP请求.而是创建一个<script>标记,其源设置为目标URL.然后将此脚本标签添加到DOM中(通常在<head>元素内).

JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead a <script> tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head> element).

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP请求:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);


JSON响应和JSONP响应之间的区别在于JSONP响应对象作为参数传递给回调函数.


The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.

{ "bar": "baz" }

JSONP:

foo( { "bar": "baz" } );


这就是为什么您看到包含callback参数的JSONP请求,以便服务器知道用于包装响应的函数名称的原因.


This is why you see JSONP requests containing the callback parameter, so that the server knows the name of the function to wrap the response.

此功能必须在全局范围存在.<script>标签由浏览器评估(一旦请求完成).

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has completed).

在处理JSON响应和JSONP响应之间要注意的另一个区别是,可以通过包装尝试评估responseText的方法来捕获JSON响应中的任何解析错误. 在try/catch语句中.由于JSONP响应的性质,响应中的解析错误将导致无法捕获的JavaScript解析错误.

Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.

两种格式都可以通过在发起请求之前设置超时并在响应处理程序中清除超时来实现超时错误.

Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.

使用 jQuery 进行JSONP请求的有用之处在于,jQuery确实做到了 为您做的所有工作 .

The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.

默认情况下,jQuery要求您在AJAX请求的URL中包含&callback=?. jQuery将采用您指定的success函数,为其分配一个唯一的名称,并将其发布到全局范围内.然后它将用为其分配的名称替换&callback=?中的问号?.

By default jQuery requires you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ? in &callback=? with the name it has assigned.

以下假定响应对象{ "bar" : "baz" }

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP:

function foo(response) {
  document.getElementById("output").innerHTML = response.bar;
};

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

这篇关于有人能用外行人解释什么是JSONP吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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