Phonethics
Phonethics

Reputation: 547

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.

Upvotes: 1

Views: 698

Answers (3)

Matt
Matt

Reputation: 894

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.

Upvotes: 1

Vincent Robert
Vincent Robert

Reputation: 36130

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

Upvotes: 6

Matt
Matt

Reputation: 75317

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.

Upvotes: 2

Related Questions