简体   繁体   中英

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=? part of your URL and automatically switches the dataType from 'json' to 'jsonp' .

JSONP is a JSON query that is not made using XMLHttpRequest but by adding a script tag to your page. Calling back into your script is handled by the caller giving the name of a JavaScript function to execute when the script loads. This is why cross-domain is working.

jQuery will handle JSONP transparently for you in a $.ajax request. The manual (and to me cleaner) way to do this is to define a 'jsonp' dataType and use the placeholder ? for the callback name in the URL. jQuery will automatically replace the ? 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=? in the URL with callback=nameItGaveTheFunction .

It then functions as a normal JSONP request; 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). This loads the JSON and then fires the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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