jQuery JSONP - 外部回调错误() [英] jQuery JSONP - error with a callback outside done()
问题描述
我正在使用jQuery 1.8.2而且我正在进行这样的JSONP调用:
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);
});
当我运行此命令时,正确的数据响应将返回到foo回调。但错误也会触发,控制台会将错误记录为错误{}
。从阅读Stackoverflow上的其他地方看来,这是因为响应包含在回调中,而jQuery期待普通的JSON。我应该忽略这个错误吗?
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?
推荐答案
你不应该有一个全局函数 foo
这是回调,但让jQuery自动创建该全局函数并传递结果到完成
回调。它确实会调用自己的函数,否则会触发错误。
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);
});
这篇关于jQuery JSONP - 外部回调错误()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!