我一直在检查以确保我的 AJAX 请求成功,方法如下:
$.post("page.php", {data: stuff}, function(data, status) {
if(status == "success") {
//Code here
}
else {
//Error handling stuff
}
});
检查状态变量是执行此操作的最佳方法,还是有更好的方法来确保请求确实通过?我认为“成功”请求是指成功命中我要发布到的页面而不会超时的请求(例如,如果服务器已关闭并且在其关闭之前发出了 AJAX 请求)或返回任何类似 404 或 500 错误。
最佳答案
通过这种方式调用 $.post
,您将自动仅在 成功处理程序
函数中传递。
如果请求出现问题,该方法甚至不会执行。
要获得更多控制,请直接使用 $.ajax()
,或传入失败处理程序。这可能看起来像
$.post("page.php", {data: stuff}, function(data, status) {
// we're fine here
}).fail(function(err, status) {
// something went wrong, check err and status
});
使用 .ajax()
实现同样的效果:
$.ajax({
type: 'POST',
url: 'page.php',
data: stuff,
success: function( data ) {
},
error: function(xhr, status, error) {
// check status && error
},
dataType: 'text'
});
您甚至可以将更多 ajax 事件处理程序传递给 $.ajax
,例如 beforeSend
来修改/读取 XHR header 或 complete
来获得当请求完成时,处理程序以两种方式(错误或非错误)触发。
关于jquery - 在 jQuery 中检查 AJAX 请求是否成功的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8138021/