I have the following Javascript code:
$.getJSON('data.jsonp?callback=abcde', function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
})
But it causes a parseError
. Here's the incoming text:
abcde({"data":"value"});
And here's the error:
SyntaxError: Unexpected token a in JSON at position 0
I'm probably missing something really obvious but I've done my research and couldn't find it. Can someone point out what I'm missing?
Try using callback=?
instead of callback=abcde
. From the documentation:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in
$.ajax()
for more details.
jQuery looks for this specific string, and then substitutes its internally-generated function name.
$.getJSON('data.jsonp?callback=?', function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
})
If you need to use your own callback function, I think you have to use $.ajax()
rather than the $.getJSON()
shortcut.
$.ajax({
url: "data.jsonp",
type: "get",
dataType: 'jsonp',
jsonp: "abcde"
})
.done(function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
});