嘿家伙我有一个简单的Jquery ajax函数调用,看起来像这样.
function getUsers(){
var jqxhr = $.ajax({
url: "../assets/js/data/users.json",
type: "GET",
cache: true,
dataType: "json",
statusCode: {
404: handleError404("Error at getUsers();"),
500: handleError500("Error at getUsers();")
},
success: function (data) {
$.each(data, function(index, element) {
console.log(element.name);
});
}
});
}
function handleError500(customMsg){
alert("Oops, there was an error: 500");
console.log("ERROR: 500 | "+customMsg);
}
function handleError404(customMsg){
alert("Oops, there was an error: 404");
console.log("ERROR: 404 | "+customMsg);
}
由于一些奇怪的原因,即使成功调用没有任何错误500或404,statusCode函数也会被触发.
有任何想法吗?谢谢.
解决方法:
这是一个常见的Javascript问题,但你实际上是在解雇这些功能!
404: handleError404() // <-- it calls it immidiately
你需要做的是创建一个匿名函数,它将在错误实际发生时稍后调用,其中的内部函数将调用你的函数.
statusCode: {
404: function () { // <-- anonymous function won't get called until it needs to
handleError404("Error at getUsers();")
},
500: function () {
handleError500("Error at getUsers();")
}
},
Side note: If you weren’t passing in parameters to your function,
you Could actually ommit the anonymous functionfunction () { /*
part, and just call your function!
function call */ }
statusCode: {
404: handleErrors, // since no parameters are passed, this Could be done
500: handleErrors
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。