如何取消/中止 jQuery AJAX 请求? [英] How to cancel/abort jQuery AJAX request?

查看:29
本文介绍了如何取消/中止 jQuery AJAX 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 AJAX 请求,它将每 5 秒发出一次.但问题是在 AJAX 请求之前,如果前一个请求未完成,我必须中止该请求并发出新请求.

I've an AJAX request which will be made every 5 seconds. But the problem is before the AJAX request if the previous request is not completed I've to abort that request and make a new request.

我的代码是这样的,怎么解决这个问题?

My code is something like this, how to resolve this issue?

$(document).ready(
    var fn = function(){
        $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

推荐答案

jquery ajax 方法返回一个 XMLHttpRequest 对象.您可以使用此对象取消请求.

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

XMLHttpRequest 有一个 abort 方法,可以取消请求,但如果请求已经发送到服务器,则服务器会处理请求,即使我们中止请求,但客户端不会等待/处理响应.

The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

xhr 对象还包含一个 readyState,其中包含请求(UNSENT-0、OPENED-1、HEADERS_RECEIVED-2、LOADING-3 和 DONE-4).我们可以用它来检查之前的请求是否完成.

The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

$(document).ready(
    var xhr;
    
    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

这篇关于如何取消/中止 jQuery AJAX 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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