问题
I'm on jQuery 1.8.2 and I'm doing a JSONP call like this:
function foo(data) {
console.log(data)
}
$.ajax({
type: 'GET',
url: http://xxx.cloudfront.net/posts.json?category=News&callback=foo,
dataType: 'jsonp',
cache: true,
jsonp: false
}).done(function (data) {
}).fail(function (XHR, status, error) {
console.log(error);
});
When I run this the proper data response gets returned to the foo callback. But the error also fires, and the console logs the error as Error {}
. From reading elsewhere on Stackoverflow it appears this is because the response is wrapped in the callback and jQuery's expecting plain JSON. Should I just ignore this error?
回答1:
You should not have a global function foo
that is the callback, but let jQuery create that global function automatically and pass the result to the done
callbacks. It does expect that its own function gets called, otherwise it triggers the error.
$.ajax({
type: 'GET',
url: "http://xxx.cloudfront.net/posts.json?category=News&callback=?",
dataType: 'jsonp',
jsonpCallback: 'foo', // for caching
cache: true
}).done(function (data) {
console.log(data);
}).fail(function (XHR, status, error) {
console.log(error);
});
回答2:
You've specifically removed the JSONP callback from your AJAX call, try omitting jsonp : false
from the options object you pass into $.ajax
and then removing the callback function you've created (foo
) and let jQuery do the work for you.
Documentation is found here: http://api.jquery.com/jquery.ajax/
来源:https://stackoverflow.com/questions/18833197/jquery-jsonp-error-with-a-callback-outside-done