检查AJAX请求在jQuery中是否成功的最佳方法 [英] Best way to check if AJAX request was successful in jQuery
问题描述
我一直在检查,以确保我的AJAX请求成功通过这样做:
I've been checking to make sure my AJAX requests are successful by doing something like this:
$.post("page.php", {data: stuff}, function(data, status) {
if(status == "success") {
//Code here
}
else {
//Error handling stuff
}
});
检查状态变量是执行此操作的最佳方法,还是有更好的方法确保请求实际通过?我正在考虑一个成功的请求,作为一个请求,我发布成功的页面,没有超时(如果服务器关闭,AJAX请求作为一个例子),或返回任何
Is checking the status variable the best way to go about doing this, or is there a better way to make sure the request actually went through? I'm considering a "successful" request to be a request that hits the page I'm posting to successfully without timing out (if the server was down and an AJAX request was made right before it went down as an example) or returning any kind of 404 or 500 error.
推荐答案
通过调用 $。post
这样,您只能在成功处理程序
函数中自动传递。
By calling $.post
that way, you automatically pass only in a success handler
function.
如果请求发生错误,方法甚至不执行。
If something on the request went wrong, this method is not even executed.
要更多的控制权直接使用 $。ajax()
失败处理程序这可能看起来像
To have more control either use $.ajax()
directly, or pass in fail handlers. That could look like
$.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标题或完成
以使处理程序以任一方式触发(错误或否)请求完成。
You can even pass more ajax event handler to $.ajax
, like beforeSend
to modify/read XHR headers or complete
to have a handler which fires either way (error or not) when the requests finished.
这篇关于检查AJAX请求在jQuery中是否成功的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!