简体   繁体   English

此跨域请求如何工作?

[英]How does this cross-domain request work?

$.ajax(
{
    url : "http://search.twitter.com/search.json?q=google&lang=en&rpp=10&since_id=&callback=?",
    dataType : 'json',
    success : function(data)
    {
        alert(data.results.length);
    }
});

How exactly is this working ? 这到底是如何工作的? I mean the cross-domain request. 我的意思是跨域请求。

jQuery detects the callback=? jQuery检测到callback=? part of your URL and automatically switches the dataType from 'json' to 'jsonp' . URL的一部分,并自动将dataType从'json'切换到'jsonp'

JSONP is a JSON query that is not made using XMLHttpRequest but by adding a script tag to your page. JSONP是不使用XMLHttpRequest而是通过将脚本标签添加到页面来进行的JSON查询。 Calling back into your script is handled by the caller giving the name of a JavaScript function to execute when the script loads. 调用者将处理返回的脚本,并提供在脚本加载时要执行的JavaScript函数的名称。 This is why cross-domain is working. 这就是跨域工作的原因。

jQuery will handle JSONP transparently for you in a $.ajax request. jQuery将在$ .ajax请求中为您透明地处理JSONP。 The manual (and to me cleaner) way to do this is to define a 'jsonp' dataType and use the placeholder ? 手动(对我来说更干净)的方法是定义一个'jsonp'数据类型并使用占位符? for the callback name in the URL. URL中的回调名称。 jQuery will automatically replace the ? jQuery会自动替换? with an appropriate value to trigger your success callback. 具有适当的值以触发您的成功回调。

$.ajax(
{
    url : "http://api.twitter.com/1/users/show/google.json&jsoncallback=?",
    dataType : 'jsonp',
    success : function(data)
    {
        alert(data.results.length);
    }
});

jQuery defines your callback function in the global scope, then substitutes callback=? jQuery在全局范围内定义您的回调函数,然后替换callback=? in the URL with callback=nameItGaveTheFunction . 在带有callback=nameItGaveTheFunction的URL中。

It then functions as a normal JSONP request; 然后,它充当普通的JSONP请求; using script tags, and wrapping the response in the callback function. 使用脚本标签,并将响应包装在回调函数中。

I believe that jQuery realises it's cross domain and so adds a script tag to the page header with the appropriate src attribute (rather than firing of an ajax request). 我相信jQuery意识到它是跨域的,因此使用适当的src属性(而不是触发ajax请求)向页眉添加了一个脚本标签。 This loads the JSON and then fires the callback. 这将加载JSON,然后触发回调。

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

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