如果 Ajax 请求失败,我想捕获错误并显示适当的消息。
我的代码如下所示,但我无法捕获失败的 Ajax 请求。
function getAjaxData(id)
{
$.post("status.ajax.php", {deviceId : id}, function(data){
var tab1;
if (data.length>0) {
tab1 = data;
}
else {
tab1 = "Error in Ajax";
}
return tab1;
});
}
我发现,当 Ajax 请求失败时,“Error in Ajax”从不执行。
如何处理 Ajax 错误并在失败时显示相应的消息?
最佳答案
从 jQuery 1.5 开始,您可以使用延迟对象机制:
$.post('some.php', {name: 'John'})
.done(function(msg){ })
.fail(function(xhr, status, error) {
// error handling
});
另一种方法是使用 .ajax
:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
关于jquery - 如何捕获 Ajax 查询发布错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2833951/