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

如何取消 / 中止 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);
    );
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • elliott.david 2013-01-31 05:45

    Why should you abort the request?

    If each request takes more than five seconds, what will happen?

    You shouldn't abort the request if the parameter passing with the request is not changing. eg:- the request is for retrieving the notification data. In such situations, The nice approach is that set a new request only after completing the previous Ajax request.

    $(document).ready(
    
        var fn = function(){
    
            $.ajax({
                url: 'ajax/progress.ftl',
                success: function(data) {
                    //do something
                },
    
                complete: function(){setTimeout(fn, 500);}
            });
        };
    
         var interval = setTimeout(fn, 500);
    
    );
    
    评论
    解决 无用
    打赏 举报
  • csdnceshi62 2013-03-26 15:25

    When you make a request to a server, have it check to see if a progress is not null (or fetching that data) first. If it is fetching data, abort the previous request and initiate the new one.

    var progress = null
    
    function fn () {    
        if (progress) {
            progress.abort();
        }
        progress = $.ajax('ajax/progress.ftl', {
            success: function(data) {
                //do something
                progress = null;
            }
        });
    }
    
    评论
    解决 无用
    打赏 举报
  • 零零乙 2013-06-12 09:39

    jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)

    var singleAjax = function singleAjax_constructor(url, params) {
        // remember last jQuery's get request
        if (this.lastInstance) {
            this.lastInstance.abort();  // triggers .always() and .fail()
            this.lastInstance = false;
        }
    
        // how to use Deferred : http://api.jquery.com/category/deferred-object/
        var $def = new $.Deferred();
    
        // pass the deferrer's request handlers into the get response handlers
        this.lastInstance = $.get(url, params)
            .fail($def.reject)         // triggers .always() and .fail()
            .success($def.resolve);    // triggers .always() and .done()
    
        // return the deferrer's "control object", the promise object
        return $def.promise();
    }
    
    
    // initiate first call
    singleAjax('/ajax.php', {a: 1, b: 2})
        .always(function(a,b,c) {console && console.log(a,b,c);});
    
    // second call kills first one
    singleAjax('/ajax.php', {a: 1, b: 2})
        .always(function(a,b,c) {console && console.log(a,b,c);});
        // here you might use .always() .fail() .success() etc.
    
    评论
    解决 无用
    打赏 举报
  • 撒拉嘿哟木头 2013-10-24 08:10

    You should also check for readyState 0. Because when you use xhr.abort() this function set readyState to 0 in this object, and your if check will be always true - readyState !=4

    $(document).ready(
        var xhr;
    
        var fn = function(){
            if(xhr && xhr.readyState != 4 && xhr.readyState != 0){
                xhr.abort();
            }
            xhr = $.ajax({
                url: 'ajax/progress.ftl',
                success: function(data) {
                    //do something
                }
            });
        };
    
        var interval = setInterval(fn, 500);
    ); 
    
    评论
    解决 无用
    打赏 举报
  • Lotus@ 2015-01-31 22:44

    I know this might be a little late but i experience similar issues where calling the abort method didnt really aborted the request. instead the browser was still waiting for a response that it never uses. this code resolved that issue.

     try {
            xhr.onreadystatechange = null;
            xhr.abort();
    } catch (e) {}
    
    评论
    解决 无用
    打赏 举报
  • MAO-EYE 2015-10-15 08:58

    You can use jquery-validate.js . The following is the code snippet from jquery-validate.js.

    // ajax mode: abort
    // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
    // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
    
    var pendingRequests = {},
        ajax;
    // Use a prefilter if available (1.5+)
    if ( $.ajaxPrefilter ) {
        $.ajaxPrefilter(function( settings, _, xhr ) {
            var port = settings.port;
            if ( settings.mode === "abort" ) {
                if ( pendingRequests[port] ) {
                    pendingRequests[port].abort();
                }
                pendingRequests[port] = xhr;
            }
        });
    } else {
        // Proxy ajax
        ajax = $.ajax;
        $.ajax = function( settings ) {
            var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
                port = ( "port" in settings ? settings : $.ajaxSettings ).port;
            if ( mode === "abort" ) {
                if ( pendingRequests[port] ) {
                    pendingRequests[port].abort();
                }
                pendingRequests[port] = ajax.apply(this, arguments);
                return pendingRequests[port];
            }
            return ajax.apply(this, arguments);
        };
    }
    

    So that you just only need to set the parameter mode to abort when you are making ajax request.

    Ref:https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js

    评论
    解决 无用
    打赏 举报
  • 七度&光 2018-09-07 20:01

    Create a function to call your API. Within this function we define request callApiRequest = $.get(... - even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined' and also if it is pending suggestCategoryRequest.state() == 'pending' - if both are true, we .abort() the request which will prevent the success callback from running.

    // We need to wrap the call in a function
    callApi = function () {
    
        //check if request is defined, and status pending
        if (typeof(callApiRequest) != 'undefined'
            && suggestCategoryRequest.state() == 'pending') {
    
            //abort request
            callApiRequest.abort()
    
        }
    
        //define and make request
        callApiRequest = $.get("https://example.com", function (data) {
    
            data = JSON.parse(data); //optional (for JSON data format)
            //success callback
    
        });
    }
    

    Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.

    You can further extend this function by adding definition of error callback - what should happen if request was aborted.

    Common use-case for this snippet would be a text input that fires on keypress event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort().

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题