views:

496

answers:

2

The $.getJSON() documentation states:

If the specified URL is on a remote server, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

The $.ajax() documentation for the jsonp data type states (emphasis mine):

Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.

So it seems that if I call $.getJSON() with a cross-domain URL, the extra "callback=?" parameter should automatically get added. (Other parts of the documentation support this interpretation.)

However, I'm not seeing that behavior. If I don't add the "callback=?" explicitly, jQuery incorrectly makes an XMLHttpRequest (which returns null data since I can't read the response cross-domain). If I do add it explicitly, jQuery correctly makes a <script> request.

Here's an example:

var URL = "http://www.geonames.org/postalCodeLookupJSON" +
    "?postalcode=10504&country=US";

function alertResponse(data, status) {
  alert("data: " + data + ", status: " + status);
}

$.getJSON(URL, alertResponse);
// alerts "data: null, status: success"

$.getJSON(URL + "&callback=?", alertResponse);
// alerts "data: [object Object], status: undefined"

So what's going on? Am I misunderstanding the documentation or forgetting something?

It goes without saying that this isn't a huge deal, but I'm creating a web API and I purposely set the callback parameter to "callback" in the hopes of tailoring it nicely to jQuery usage.

Thanks!

(Edit: I cross-posted this in the jQuery forums if you're interested.)

+1  A: 

Try this:

var URL = "http://www.geonames.org/postalCodeLookupJSON" +
    "?postalcode=10504&country=US";
function alertResponse(data, status) {
    alert("data: " + data + ", status: " + status);
}
$.ajax({
    url: URL,
    dataType: 'jsonp',
    jsonp: 'alertResponse',
});
PetersenDidIt
In your example, you actually mean `jsonpCallback: 'alertResponse'`, and yes, that works then without me having to explicitly add the "callback=?" parameter. But that's so much more verbose than the elegance of `$.getJSON()`. It'd be nice if `$.getJSON()` worked as documented...
Aseem Kishore
A: 

Yes, I think you misunderstood. $.getJSON is a shortcut for $.ajax({datatype: 'json'.... as the documentation says. It never makes a JSONP call unless you add the callback=? parameter.

Chetan Sastry
Hmm... did I really misunderstand? The sentence I quoted is pretty explicit: "If the specified URL is on a remote server, the request is treated as JSONP instead."
Aseem Kishore
You're right. That's confusing.
Chetan Sastry