It's actually not too complicated...(实际上并不太复杂...)
Say you're on domain example.com
, and you want to make a request to domain example.net
.(假设您使用的是example.com
域,并且想向example.net
域发出请求。)
To do so, you need to cross domain boundaries, a no-no in most of browserland.(要做到这一点,你需要跨域边界, 无无多数browserland的。)
The one item that bypasses this limitation is <script>
tags.(绕过此限制的一项是<script>
标记。)
When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.(使用脚本标记时,将忽略域限制,但是在正常情况下,您实际上无法对结果做任何事情,只是对脚本进行了评估。)
Enter JSONP
.(输入JSONP
。)
When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page.(当您向启用JSONP的服务器发出请求时,您将传递一个特殊参数,该参数告诉服务器有关您页面的一些信息。) That way, the server is able to nicely wrap up its response in a way that your page can handle.(这样,服务器就可以用页面可以处理的方式很好地包装其响应。)
For example, say the server expects a parameter called callback
to enable its JSONP capabilities.(例如,假设服务器需要一个名为callback
的参数来启用其JSONP功能。)
Then your request would look like:(然后您的请求将如下所示:)
http://www.example.net/sample.aspx?callback=mycallback
Without JSONP, this might return some basic JavaScript object, like so:(没有JSONP,这可能会返回一些基本的JavaScript对象,如下所示:)
{ foo: 'bar' }
However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:(但是,使用JSONP时,服务器收到“ callback”参数时,其包装结果会有所不同,返回如下所示:)
mycallback({ foo: 'bar' });
As you can see, it will now invoke the method you specified.(如您所见,它现在将调用您指定的方法。)
So, in your page, you define the callback function:(因此,在页面中,您定义了回调函数:)
mycallback = function(data){
alert(data.foo);
};
And now, when the script is loaded, it'll be evaluated, and your function will be executed.(现在,加载脚本后,将对其进行评估,然后将执行您的函数。)
Voila, cross-domain requests!(瞧,跨网域要求!)
It's also worth noting the one major issue with JSONP: you lose a lot of control of the request.(值得注意的是JSONP的一个主要问题:您失去了对请求的大量控制。)
For example, there is no "nice" way to get proper failure codes back.(例如,没有“不错”的方法来找回正确的故障代码。) As a result, you end up using timers to monitor the request, etc, which is always a bit suspect.(结果,您最终会使用计时器来监视请求等,这总是让人怀疑。) The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.(JSONRequest的主张是一个很好的解决方案,它允许跨域脚本编写,维护安全性并允许对请求的适当控制。)
These days (2015), CORS is the recommended approach vs. JSONRequest.(如今(2015年),与JSONRequest相比, CORS是推荐的方法。)
JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.(JSONP对于较旧的浏览器支持仍然有用,但是考虑到安全隐患,除非您别无选择,否则CORS是更好的选择。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…