James
James

Reputation: 2253

jQuery $.getJSON() Fails

I keep getting errors using $.getJSON(). I'm using JSONP. Here's the code:

$.getJSON('http://s3.amazonaws.com/eloqu/TestFile.js?callback=?', function(data){
    console.log(data);
})
.fail(function( jqxhr, textStatus, error ) {
    console.log( "Request Failed: " + textStatus + ', ' + error);
});

All I get is a 'parsererror'. If i change the end of the url to callback=mycallback, I just get 'error', without the type.

Upvotes: 0

Views: 2477

Answers (2)

Jason P
Jason P

Reputation: 27012

This is a bit of an odd situation...

Here's a working fiddle.. I had to define the mycallback function:

http://jsfiddle.net/xtKAb/

$(document).ready(function () {
    $.getJSON('http://s3.amazonaws.com/eloqu/TestFile.js?callback=?');
});

function mycallback(data) {
    console.log(data);
}

I think the problem is that the remote file is static. Generally, you send the callback you want, and the remote service wraps the data in the callback you specify. Here's an example of the actual request jQuery makes:

http://s3.amazonaws.com/eloqu/TestFile.js?callback=jQuery20209767435337416828_1376014401926&_=1376014401927

So jQuery is expecting the callback to be jQuery20209767435337416828_1376014401926(), but that doesn't happen (because the remote file is static). Since the data doesn't get to the callback that jQuery is expecting, it most likely tries to json parse an undefined object, which is giving you the parse error.

Upvotes: 1

Vincent Duprez
Vincent Duprez

Reputation: 3892

Your return looks like this :

mycallback({ "test": "variable", "test2": "variable2" })

while a valid json would be:

{ "test": "variable", "test2": "variable2" }

A valid json can only start with an array sign [ or an object sign { you can validate any json string on http://jsonlint.com

Upvotes: 0

Related Questions