我有一个使用 jquery ajax 调用的 webmethod。我点击了错误回调。很好 - 我以为我会分析错误 - 但它是未定义的。
错误值未定义的可能性有哪些?如果这是一个微不足道的错误,如何解决这个问题?
注意:xhr
、status
和 error
未定义。
注意:我使用的是 Chrome 版本 35 和 IE 8
代码
$(document).ready(function () {
function errorFunction(xhr, status, error) {
console.log(xhr);
if (xhr == 'undefined' || xhr == undefined) {
alert('undefined');
} else {
alert('object is there');
}
alert(status);
alert(error);
}
$.ajax({
type: "POST",
url: "admPlantParametersViewEdit.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
alert(msg.d);
},
error: errorFunction()
});
});
最佳答案
您需要传递对函数的引用,因此更改此:
error: errorFunction()
对此:
error: errorFunction
当你把括号放在那里时,你实际上是立即调用该函数并传递它的返回值。如果没有括号,它只是对稍后可由 jQuery ajax 基础结构调用的函数的引用。
为了进一步了解发生的情况,您的代码 error: errorFunction()
立即调用 errorFunction()
且不带任何参数(这就是您在调试中看到的情况) ),然后从该函数获取返回值(未定义
),然后将其放入传递给 ajax 调用的数据结构中。所以本质上,你所做的相当于:
$(document).ready(function () {
function errorFunction(xhr, status, error) {
console.log(xhr);
if (xhr == 'undefined' || xhr == undefined) {
alert('undefined');
} else {
alert('object is there');
}
alert(status);
alert(error);
}
// obviously, not what you intended
errorFunction();
$.ajax({
type: "POST",
url: "admPlantParametersViewEdit.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
alert(msg.d);
},
// also not what you intended
error: undefined
});
});
如果您没有在其他地方使用 errorFunction()
,那么更常见的方法是像使用 success
处理程序一样内联定义它像这样:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "admPlantParametersViewEdit.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
alert(msg.d);
},
error: function(xhr, status, error) {
console.log(xhr);
if (xhr == 'undefined' || xhr == undefined) {
alert('undefined');
} else {
alert('object is there');
}
alert(status);
alert(error);
}
});
});
关于javascript - jQuery Ajax 错误对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24174404/