开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜