【问题标题】:Best way to check if AJAX request was successful in jQuery在 jQuery 中检查 AJAX 请求是否成功的最佳方法
【发布时间】:2011-12-29 14:18:35
【问题描述】:

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

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

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

【问题讨论】:

  • 你认为什么是成功的?是建立了连接并返回了数据,还是您服务器上的脚本确实按照您的意愿行事?根据您的使用情况,您可能还需要检查实际响应。
  • 编辑了我的问题以解释我认为成功的原因

标签: jquery ajax error-handling


【解决方案1】:

通过这种方式调用$.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
});

同样的事情使用.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 标头或 complete 以拥有一个在请求完成时触发任一方式(错误与否)的处理程序。

【讨论】:

  • 非常适合为我处理丢失参数的错误处理(.post 方法)...感谢 jAndy。
【解决方案2】:

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

您可以检查它何时返回"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";
...
        }
    }

【讨论】:

    【解决方案3】:

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

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

    我也推荐使用firebug或类似的webkit,然后你可以跟踪请求并检查参数!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 2018-01-15
      • 2012-01-20
      • 2015-05-27
      • 1970-01-01
      相关资源
      最近更新 更多