简体   繁体   English

jQuery的ajax crossDomain属性的用法?

[英]Usages of jQuery's ajax crossDomain property?

According to jQuery : 根据jQuery:

crossDomain (default: false for same-domain requests, true for cross-domain requests) Type: Boolean If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. crossDomain (default: false for same-domain requests, true for cross-domain requests)类型:Boolean如果要在同一域上强制执行跨域请求(如JSONP),请将crossDomain的值设置为true。 This allows, for example, server-side redirection to another domain. 例如,这允许服务器端重定向到另一个域。 (version added: 1.5) (版本增加:1.5)

I don't understand the above. 我不明白以上。

If the code is 如果代码是

$(document).ready(function ()
{
    $.ajax(
    {
        url: 'http://es3.com/Handlers/MyHandler.ashx',
        cache: false,
        dataType: "jsonp",
        ...
        ...
    });
});

function aaa(json)
{
    alert(json.result);
}

And im specifiying datatype:jsonp , then the response is going to be application/javascript mime typed , becuase it's a script which will run in my browser. 并且我指定datatype:jsonp ,然后响应将是application / javascript mime typed,因为它是一个将在我的浏览器中运行的脚本。

I dont see any reason why it would not act like that when I'm running this code under the same domain. 当我在同一个域下运行此代码时,我没有看到任何理由为什么它不会那样 ( hence - I don't see the usages for this property). (因此 - 我没有看到这个属性的用法)。

I have made a sample 我做了一个样本

I have 2 (host tweaked) domains. 我有2个(主机调整)域名。 es2.com and es3.com . es2.comes3.com

(notice , the url in the code is always to es3.com ) (注意,代码中的url始终是es3.com

Test #1 : 测试#1:

Run the code from es3.com : (left pane) es3.com运行代码:(左窗格)
Run the code from es2.com : (right pane) es2.com运行代码:(右窗格)
crossDomain:false (default when missing). crossDomain:false (缺少时默认)。

look at the differences : ( http://i.stack.imgur.com/RKyZp.jpg ) 看看差异:( http://i.stack.imgur.com/RKyZp.jpg

在此输入图像描述

Test #2 : 测试#2:

Run the code from es3.com : (left pane) es3.com运行代码:(左窗格)
Run the code from es2.com : (right pane) es2.com运行代码:(右窗格)
crossDomain:true <--- notice crossDomain:true <---通知

( http://i.stack.imgur.com/xEcyd.jpg ) http://i.stack.imgur.com/xEcyd.jpg 在此输入图像描述

I don't see any difference. 我没有看到任何区别。

Question : 题 :

Why / When do I need to set the crossDomain property ? 为什么/何时需要设置crossDomain属性?

The default for crossDomain is as follows: crossDomain默认值如下:

false for same-domain requests, true for crossDomain requests 对于同域请求为false,对于跨域请求为true

The data-type is interpreted differently depending on the value for the crossDomain setting: 根据crossDomain设置的值, data-type的解释会有所不同:

"json": Evaluates the response as JSON and returns a JavaScript object. “json”:将响应计算为JSON并返回JavaScript对象。 Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options 跨域“json”请求将转换为“jsonp”,除非请求选项中包含jsonp:false

Because you are using jsonp instead of json you won't see any difference in your tests. 因为您使用的是jsonp而不是json ,所以在测试中看不出任何差异。

When do I need to set the crossDomain property ? 我什么时候需要设置crossDomain属性?

If you are making a same domain json request, and your site may redirect the request to another domain to serve the response (via HTTP 3XX), then you should set the crossDomain property to true so the response can be read by your calling script. 如果您正在进行相同的域json请求, 并且您的站点可能会将请求重定向到另一个域以提供响应(通过HTTP 3XX),那么您应该将crossDomain属性设置为true,以便您的调用脚本可以读取响应。

This gives you the advantage of retrieving JSON when making same origin requests, and the functionality of JSONP when making cross-origin requests. 这使您可以在进行相同的原始请求时检索JSON,并在进行跨源请求时检索JSONP的功能。 If CORS is active on the domain you redirect to then you can set jsonp: false in the request options. 如果CORS在您重定向到的域上处于活动状态,则可以在请求选项中设置jsonp: false

Examples 例子

Making a request from example.com to example.org. 从example.com向example.org发出请求。

  • crossDomain automatically set to true. crossDomain自动设置为true。
  • Data type set to jsonp . 数据类型设置为jsonp

Result: JSONP returned by example.org. 结果: example.org返回JSONP。

Making a request from example.com to example.com. 从example.com向example.com发出请求。

  • crossDomain automatically set to false. crossDomain自动设置为false。
  • Data type set to jsonp . 数据类型设置为jsonp

Result: JSONP returned by example.com. 结果: example.com返回JSONP。

Making a request from example.com to example.org. 从example.com向example.org发出请求。

  • crossDomain automatically set to true. crossDomain自动设置为true。
  • Data type set to json . 数据类型设置为json

Result: JSONP returned by example.org. 结果: example.org返回JSONP。

Making a request from example.com to example.com. 从example.com向example.com发出请求。

  • crossDomain automatically set to false. crossDomain自动设置为false。
  • Data type set to json . 数据类型设置为json

Result: JSON returned by example.com. 结果: example.com返回JSON。

Making a request from example.com to example.org. 从example.com向example.org发出请求。

  • crossDomain automatically set to true. crossDomain自动设置为true。
  • Data type set to json . 数据类型设置为json
  • jsonp is set to false. jsonp设置为false。
  • example.org does not support CORS for example.com example.org不支持example.com的CORS

Result: CORS error returned by browser. 结果:浏览器返回CORS错误。

Making a request from example.com to example.com, example.com redirects AJAX to example.edu. 从example.com向example.com发出请求,example.com将AJAX重定向到example.edu。

  • crossDomain manually set to true. crossDomain手动设置为true。
  • Data type set to json . 数据类型设置为json

Result: JSONP returned by example.edu. 结果: example.edu返回JSONP。

Making a request from example.com to example.org. 从example.com向example.org发出请求。

  • crossDomain automatically set to true. crossDomain自动设置为true。
  • Data type set to json . 数据类型设置为json
  • jsonp is set to false. jsonp设置为false。
  • example.org does support CORS for example.com example.org支持example.com的CORS

Result: JSON returned by example.org. 结果: example.org返回JSON。

Making a request from example.com to example.com, example.com redirects AJAX to example.edu. 从example.com向example.com发出请求,example.com将AJAX重定向到example.edu。

  • crossDomain automatically set to false. crossDomain自动设置为false。
  • Data type set to json . 数据类型设置为json
  • example.edu does not support CORS for example.com example.edu不支持example.com的CORS

Result: CORS error returned by browser. 结果:浏览器返回CORS错误。

Lets assume , you have have another domain spanish.es2.com which serves spanish users of your website. 让我们假设,您有另一个域名spanish.es2.com ,它为您网站的西班牙用户提供服务。

You have the following requirement : 您有以下要求:

  1. Having a webpage on es2.com es2.com上有一个网页

  2. Call an api on es2.com and pass it some user info ( or cookie ), and get some user data. es2.com上调用api并传递一些用户信息(或cookie),并获取一些用户数据。 But if the user is spanish, the api on spanish.es2.com needs to be called for same data. 但如果用户是西班牙语,则需要为spanish.es2.com上的api调用相同的数据。

  3. When you do an ajax request with jQuery from es2.com to es2.com, for a spanish user : 对于西班牙语用户,当您使用jQuery从es2.com到es2.com执行ajax请求时:

    (a) With crossdomain disabled : Your es2.com api will find that the user is spanish, and hence do a http redirect to spanish.es2.com , which will not work due to ajax same domain policy and the ajax would fail. (一)随着crossdomain禁用:您es2.com API会发现,用户是西班牙人,因此做一个HTTP重定向到spanish.es2.com ,这将无法正常工作,由于阿贾克斯同域策略和AJAX会失败。 Redirects in ajax url -> Disallowed. 重定向在ajax网址 - >不允许。

    (b) With crossdomain enabled : Your es2.com api's jsonp response,is actually loaded as a script tag wrapped in a function, hence a http redirect to other domain does not matter, and the content is still loaded, hence the ajax works. (b)与crossdomain启用:您es2.com API的JSONP响应,实际上是加载脚本标签包装在一个功能,因此一个HTTP重定向到其他域不要紧,内容仍然加载,因此Ajax的工作原理。 Redirects in src of a script tag -> Allowed. 重定向脚本标记的src - >允许。

Hope this makes it clear. 希望这说清楚。

As far as I can see the op is correct. 据我所知,操作是正确的。 Setting dataType to jsonp will create a JSONP type request; 将dataType设置为jsonp将创建JSONP类型请求; with the result written into a script block and run. 将结果写入脚本块并运行。 Therefore forcing JSONP by setting cross-domain to true seems redundant. 因此,通过将跨域设置为true来强制JSONP似乎是多余的。

However. 然而。 The documentation says that "if you want to force a cross-domain request such as JSONP" thus implying that there might be other cases where you might want to force cross-domain behaviour. 文档说“如果你想强制执行跨域请求,例如JSONP”,那么暗示可能存在其他可能需要强制跨域行为的情况。 I'm not sure what those cases might be however. 我不确定那些情况可能是什么。

It isn't default false when missing. 丢失时不是默认的false。 When missing it defaults to true if the domains are not the same (as in your first sample above). 如果缺少它,则默认为true,如果域不相同(如上面的第一个示例中所示)。 I think you can leave it to its default value in nearly if not all cases. 我认为你可以在几乎所有的情况下将其保留为默认值。

Also, when setting the cross-domain parameter, JQuery attempts to use CORS by default, not JSONP. 此外,在设置跨域参数时,JQuery默认尝试使用CORS,而不是JSONP。

Here are some relevant snippets from JQuery source: https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js 以下是JQuery源代码的一些相关摘录: https//github.com/jquery/jquery/blob/master/src/ajax/xhr.js

variable "xhrSupported"... 变量“xhrSupported”......

xhrSupported = jQuery.ajaxSettings.xhr();

..is used to check for CORS support.... ..用于检查CORS支持....

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );

.. which is checked when making AJAX calls.... ..在进行AJAX调用时检查....

jQuery.ajaxTransport(function( options ) {
        var callback;

        // Cross domain only allowed if supported through XMLHttpRequest
        if ( support.cors || xhrSupported && !options.crossDomain ) 

Hope this helps! 希望这可以帮助!

If your are already specifying JSONP, then the crossDomain parameter doesn't do much. 如果您已经指定了JSONP,那么crossDomain参数不会做太多。 It just tells jQuery to ask for JSONP even if it's a local domain. 它只是告诉jQuery要求JSONP,即使它是一个本地域。

Let's say you are working on your machine with a local service that returns JSON or JSONP. 假设您正在使用返回JSON或JSONP的本地服务处理您的计算机。 You can use a plain $.ajax() call, which works fine. 您可以使用普通的$.ajax()调用,它可以正常工作。 In production however, the server redirects your request to a different domain if you meet some special conditions. 但是,在生产中,如果您遇到某些特殊情况,服务器会将您的请求重定向到其他域。 Prod needs to ask for JSONP, because sometimes the response comes from off-domain. Prod需要请求JSONP,因为有时响应来自域外。

Making that $.ajax() call without crossDomain: true or datatype: 'jsonp' will assume the response can be plain JSON, so the code will fail in production. 在没有crossDomain: true情况下进行$.ajax()调用crossDomain: truedatatype: 'jsonp'将假定响应可以是普通的JSON,因此代码将在生产中失败。

You can also get cross-domain XML through prestidigitation like loading cross-domain XML through JSONP with YQL , which is really just wrapping it in JSONP . 您还可以通过预处理来获取跨域XML,例如通过JQL 通过YQL加载跨域XML ,这实际上只是将其包装在JSONP中

You're question has been very helpful for me to understand the problem that I've encountering on the use of jsonp with jQuery. 你的问题对我理解我在使用jsonp jQuery时遇到的问题非常有帮助。
In my case, I needed to do a JSONP call to an external domain. 就我而言,我需要对外部域进行JSONP调用。
But the url needed to be constructed from our domain. 但是网址需要从我们的域构建。

For example, here, i assume my website is under es2.com 例如,在这里,我假设我的网站在es2.com下

JSONP call on es2.com JSONP呼叫es2.com
es2.com redirect to es3.com?newConstructedUrl=someRandomValue es2.com重定向到es3.com?newConstructedUrl=someRandomValue
es3.com?newConstructedUrl=NewCoolValue redirect to es2.com es3.com?newConstructedUrl=NewCoolValue重定向到es2.com
es2.com respond setting a new cookie in the response es2.com响应在响应中设置新的cookie

The code was working fine in localhost, but we had no cookie in the es2 environment. 代码在localhost中正常工作,但我们在es2环境中没有cookie。
And seeing the Debugger, the request was being done in XHR in the es2 environment 看到调试器,请求是在es2环境中的XHR中完成的
We needed then to set the crossDomain parameter to true. 然后我们需要将crossDomain参数设置为true。 The JSONP request was then, done even in es2.com 然后,即使在es2.com中也完成了JSONP请求

Hope my use case is clear ! 希望我的用例很明确!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM