jQuery:处理失败的 AJAX 请求的回退 [英] jQuery: Handle fallback for failed AJAX Request

查看:24
本文介绍了jQuery:处理失败的 AJAX 请求的回退的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery 能否为失败的 AJAX 调用提供回退?这是我的尝试:

Can jQuery provide a fallback for failed AJAX calls? This is my try:

function update() {
    var requestOK = false;

    $.getJSON(url, function(){
        alert('request successful');
        requestOK = true;
    });

    if (!requestOK) {
        alert('request failed');
    }
}

不幸的是,即使调用了 $.getJSON() 方法的回调函数,我也会在回调函数有机会设置 requestOK 变量之前收到消息请求失败".我认为这是因为代码并行运行.有没有办法处理这种情况?我考虑过链接或某种等待 AJAX 请求的方式,包括它的回调函数.但是如何?有人知道怎么做吗?

Unfortunately, even if the callback function of the $.getJSON() method is called, i get the message 'request failed', before the callback function has the opportunity to set the requestOK variable. I think it's because the code runs in parallel. Is there a way to handle such situations? I thought about chaining or some way of waiting for the AJAX request, including its callback function. But how? Does anyone know how to do that?

推荐答案

您将需要使用较低级别的 $.ajax 调用,或 ajaxError 函数.这是 $.ajax 方法:

You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:

function update() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000,
    success: function(data, textStatus ){
       alert('request successful');
    },
    fail: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}

EDIT 我在 $.ajax 调用中添加了一个 timeout 并将其设置为 5 秒.

EDIT I added a timeout to the $.ajax call and set it to five seconds.

这篇关于jQuery:处理失败的 AJAX 请求的回退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆