【问题标题】:Is there a way to make jquery's ajaxError stop running after the first ajax request failure?有没有办法让 jquery 的 ajaxError 在第一次 ajax 请求失败后停止运行?
【发布时间】:2019-01-08 10:33:53
【问题描述】:

场景:我有一个发出各种 ajax 请求的 Web 应用程序。其中一些是由于用户交互而发生的(例如,单击表中的一行,它会运行 ajax 请求以更新行内的更多详细信息)。其他是“后台任务”(例如检查是否有新的下载可用)。

用户必须登录到我的应用程序才能执行任何功能;因此,如果用户退出,任何 ajax 请求都会失败。

所以 ajax 请求可能是这样的:

  • /click-table-row
  • /check-downloads
  • /some-other-functionality
  • ...

我已将以下内容添加到全局 .js 文件中:

$(function() {

$( document ).ajaxError(function() {
    swal({
        position: 'top-end',
        toast: true,
        title: 'Network error',
        html: 'Please try again. If problem persists please login again.',
        type: 'error',
        confirmButtonText: 'Close'
    });
});

});

这是使用SweetAlert (swal) 在任何ajax 请求通过使用jquery 的ajaxError 失败时显示消息。

如果我模拟 ajax 请求失败 - 通过在单独的浏览器选项卡中运行我的注销脚本 - 然后让应用程序发出 ajax 请求,它将在每次发出 ajax 请求时执行 ajaxError 中的代码(可能是尝试运行的后台任务,或尝试与应用程序交互的用户)。例如,如果有 3 个请求,如问题顶部的列表所示,它将执行 swal 代码 3 次。我认为这在技术上是正确的,因为 3 个 ajax 请求确实失败了。

我想做的是想出一种方法来实现:“如果第一个 ajax 请求失败,请停止再次运行 ajaxError() 内的代码”。

我不知道这是否或如何实现?请有人建议。

jquery 3.2.1,SweetAlert 2

【问题讨论】:

标签: javascript jquery ajax sweetalert2


【解决方案1】:

检查状态码=> 401

$(document).ajaxError(function(e, xhr) {
if(xhr.status===401)
    {
    swal({
         position: 'top-end',
         toast: true,
         title: 'Network error',
         html: 'Please try again. If problem persists please login again.',
         type: 'error',
         confirmButtonText: 'Close'
        });
    }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多