如果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请求失败时,“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");
}
});
如果你想使用.then(),它与.done()相比有细微的区别:
return $.post(url, payload)
.then(
function (result, textStatus, jqXHR) {
return result;
},
function (jqXHR, textStatus, errorThrown) {
return console.error(errorThrown);
});