Question

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.)

Was it helpful?

Solution 2

Turns out this was a bug in the jQuery documentation. See http://forum.jquery.com/topic/getjson-isn-t-automatically-appending-callback-to-my-cross-domain-url for details.

OTHER TIPS

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',
    jsonpCallback: 'alertResponse',
});

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.

I am using below code,

$.ajax({ url: URL, dataType: 'jsonp', success: function ( data ) { // do something } error: function (jqXHR, textStatus, errorThrown) { }, jsonpCallback: 'login_callback', });

But, callback sometimes gets appended at the end of the url and sometimes not in IE. While its working fine in chrome and FF.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top