Search code examples
javascriptjqueryajaxjsonjsonp

Failing to get remote JSON using JSONP


I'm trying to retrieve a remote JSON using jQuery 1.11.1. The remote server does support jsonp and I'm able to download the .jsonp file by simply entering the call address and ?callback=foo in a browser.

However, when I try to get it using ajax, it fails.

$.ajax({
    type: "GET",
    url: "http://path-to-remote-server.net/file.jsonp",
    dataType: 'jsonp',
    jsonp : "callback",
    jsonpCallback: "e",
    success: function(r) {
        console.log(r);
    }
});

A quick look at the console tells me that it's a bad request, probably because it seems that jQuery passes a second unwanted parameter, making the request look like this :

http://path-to-remote-server.net/file.jsonp?callback=e&_=1406722474006

This happens even when I omit the jsonp and jsonpCallback options. The request then looks like this :

http://path-to-remote-server.net/file.jsonp?callback=jQuery111106199050471186638_1406722685544&_=1406722685545

Using the short cut $.getJSON doesn't work either, but not for the same reason it seems :

$.getJSON("http://path-to-remote-server.net/file.jsonp?callback=e", function(r){
    console.log(r);
});

This doesn't trigger any error in the console, but nothing gets logged either, as if it didn't get anything back from the server.

Why is that, and how can I avoid it?

Thank you all in advance!


Solution

  • From the manual:

    cache (default: true, false for dataType 'script' and 'jsonp')
    Type: Boolean
    If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

    So add cache: true to your Ajax parameters.