我使用了一个名为jquery ajax的web方法。我点击错误回调。很好 - 我以为我会分析错误 - 但它是未定义的。
错误值未定义的可能性有多大?如果这是一个微不足道的错误,如何解决这个问题?
注意:xhr
,status
和error
未定义。
注意:我使用的是Chrome版本35和IE 8
CODE
$(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()
});
});
答案 0 :(得分:5)
您需要传递对该函数的引用,因此请更改:
error: errorFunction()
到此:
error: errorFunction
当你把parens放在那里时,你实际上是立即调用函数并传递它的返回值。没有parens,它只是对jQuery ajax基础结构稍后可以调用的函数的引用。
为了进一步了解发生了什么,您的代码error: errorFunction()
立即调用errorFunction()
,没有参数(这是您在调试中看到的),然后从该函数中获取返回值(是undefined
)然后将其放入传递给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);
}
});
});