views:

143

answers:

3
$.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.

+1  A: 

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.

Matt
Phonethics
+1  A: 

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.

Matt
+4  A: 

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);
    }
});
Vincent Robert