Aar*_*ron 15 ajax error-handling jquery
我一直在检查以确保我的AJAX请求成功通过这样做:
$.post("page.php", {data: stuff}, function(data, status) {
if(status == "success") {
//Code here
}
else {
//Error handling stuff
}
});
Run Code Online (Sandbox Code Playgroud)
检查状态变量是执行此操作的最佳方式,还是有更好的方法来确保请求实际执行?我正在考虑一个"成功"的请求是一个请求,它命中我正在成功发布的页面没有超时(如果服务器已经关闭,并且在它作为一个例子之前发出了一个AJAX请求)或者返回任何有点404或500错误.
jAn*_*ndy 30
通过$.post这种方式调用,您只能自动传递一个success handler函数.
如果请求中的某些内容出错,则此方法甚至不会执行.
要有更多控制要么$.ajax()直接使用,要么传入失败处理程序.这可能看起来像
$.post("page.php", {data: stuff}, function(data, status) {
// we're fine here
}).fail(function(err, status) {
// something went wrong, check err and status
});
Run Code Online (Sandbox Code Playgroud)
使用相同的东西.ajax():
$.ajax({
type: 'POST',
url: 'page.php',
data: stuff,
success: function( data ) {
},
error: function(xhr, status, error) {
// check status && error
},
dataType: 'text'
});
Run Code Online (Sandbox Code Playgroud)
你甚至可以传递更多的ajax事件处理程序$.ajax,比如beforeSend修改/读取XHR头文件或者complete让一个处理程序在请求完成时以任何一种方式触发(错误与否).
| 归档时间: |
|
| 查看次数: |
65218 次 |
| 最近记录: |