在 jQuery 中检查 AJAX 请求是否成功的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8138021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:05:53  来源:igfitidea点击:

Best way to check if AJAX request was successful in jQuery

jqueryajaxerror-handling

提问by Aaron

I've been checking to make sure my AJAX requests are successful by doing something like this:

我一直在通过执行以下操作来检查以确保我的 AJAX 请求成功:

$.post("page.php", {data: stuff}, function(data, status) {
    if(status == "success") {
        //Code here
    }
    else {
        //Error handling stuff
    }
});

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.

检查状态变量是执行此操作的最佳方法,还是有更好的方法来确保请求实际通过?我正在考虑将一个“成功”请求作为一个请求,该请求命中我成功发布的页面而不会超时(如果服务器已关闭并且在它关闭之前发出了 AJAX 请求作为示例)或返回任何一种 404 或 500 错误。

回答by jAndy

By calling $.postthat way, you automatically pass only in a success handlerfunction.

通过$.post这种方式调用,您只会自动传入一个success handler函数。

If something on the request went wrong, this method is not even executed.

如果请求上的某些内容出错,则该方法甚至不会执行。

To have more control either use $.ajax()directly, or pass in fail handlers. That could look like

要获得更多控制,请$.ajax()直接使用或传入失败处理程序。那可能看起来像

$.post("page.php", {data: stuff}, function(data, status) {
   // we're fine here
}).fail(function(err, status) {
   // something went wrong, check err and status
});

The same thing using .ajax():

同样的事情使用.ajax()

$.ajax({
   type: 'POST',
   url: 'page.php',
   data: stuff,
   success: function( data ) {
   },
   error: function(xhr, status, error) {
      // check status && error
   },
   dataType: 'text'
});

You can even pass more ajax event handler to $.ajax, like beforeSendto modify/read XHR headers or completeto have a handler which fires either way (error or not) when the requests finished.

您甚至可以将更多的 ajax 事件处理程序传递给$.ajax,例如beforeSend修改/读取 XHR 标头或complete拥有一个在请求完成时以任何一种方式(错误或不)触发的处理程序。

回答by Andrew Dover

I prefer to use the ajax call, as it has an explicit success handler

我更喜欢使用 ajax 调用,因为它有一个明确的成功处理程序

$.ajax({
url: "page.php",
data: stuff,
success: function(response){
console.log("success");
}
});

I'd also recommend using firebug or webkit similar, then you can track the requests and check the parameters!

我还建议使用类似的 firebug 或 webkit,然后您可以跟踪请求并检查参数!

回答by pimvdb

jQuery considers "successful" in the way it is in the source code, of course. This does not include a status code of 404/500 and neither a timeout, since no status code has been returned in that case.

当然,jQuery 认为它在源代码中的方式是“成功的”。这不包括 404/500 的状态代码,也不包括超时,因为在这种情况下没有返回状态代码。

You can check when exactly it returns "success":

您可以检查它何时返回"success"

// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {

...
    // If not modified
    if ( status === 304 ) {

        statusText = "notmodified";
...

    // If we have data
    } else {

        try {
...
            statusText = "success"; // So: only when status code is in
                                    // the range 200 <= x < 300
...
        } catch(e) {
...
            statusText = "parsererror";
...
        }
    }