TTC*_*TCG 200 ajax error-handling jquery post
如果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;
});
}
Run Code Online (Sandbox Code Playgroud)
我发现,当Ajax请求失败时,永远不会执行"Ajax中的错误".
如果失败,我如何处理Ajax错误并显示相应的消息?
cho*_*ise 286
从jQuery 1.5开始,您可以使用延迟对象机制:
$.post('some.php', {name: 'John'})
.done(function(msg){ })
.fail(function(xhr, status, error) {
// error handling
});
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用.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");
}
});
Run Code Online (Sandbox Code Playgroud)
Mic*_*ble 281
jQuery 1.5添加了延迟对象,可以很好地处理这个问题.$.post在通话结束后,只需致电并附上您想要的任何处理程序.延迟对象甚至允许您附加多个成功和错误处理程序.
例:
$.post('status.ajax.php', {deviceId: id})
.done( function(msg) { ... } )
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
Run Code Online (Sandbox Code Playgroud)
在此之前的jQuery 1.8,该函数done被调用success和fail被调用error.
jAn*_*ndy 88
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
},
success: function(data){
// your code from above
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
Run Code Online (Sandbox Code Playgroud)
mar*_*ery 14
$.post('someUri', { },
function(data){ doSomeStuff })
.fail(function(error) { alert(error.responseJSON) });
Run Code Online (Sandbox Code Playgroud)
kar*_*m79 13
一种简单的方法是实现ajaxError:
每当Ajax请求因错误而完成时,jQuery都会触发ajaxError事件.已经使用.ajaxError()方法注册的任何和所有处理程序都会在此时执行.
例如:
$('.log').ajaxError(function() {
$(this).text('Triggered ajaxError handler.');
});
Run Code Online (Sandbox Code Playgroud)
我建议阅读ajaxError文档.它不仅仅是上面演示的简单用例 - 主要是它的回调接受了许多参数:
$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).text('Triggered ajaxError handler.');
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
365005 次 |
| 最近记录: |