斗士狗 2010-12-29 03:04 采纳率: 0%
浏览 380
已采纳

如何取消 / 中止 jQuery 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);
);

转载于:https://stackoverflow.com/questions/4551175/how-to-cancel-abort-jquery-ajax-request

  • 写回答

8条回答 默认 最新

  • ℡Wang Yan 2010-12-29 03:05
    关注

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

    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.

    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);
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程