How to cancel/abort jQuery AJAX request?

后端 未结 8 2135
时光说笑
时光说笑 2020-11-22 09:30

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

8条回答
  •  不知归路
    2020-11-22 10:31

    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

提交回复
热议问题