Get latest ajax request and abort others

我只是一个虾纸丫 提交于 2019-12-09 00:30:39

问题


I have been searching and this problem seems simple but cannot find answer. I have multiple request calling different url. But for each url, I only want the result once and it must be the last one in the same url being called. My issue now is "how to get the last one only?" I looked at this and it seems to be 3 years old:

http://plugins.jquery.com/project/ajaxqueue

Any other way to do this nicely and cleanly? If there is something like this, it would be perfect:

queue: "getuserprofile",
cancelExisting: true

(where the existing ajax in getuserprofile queue will be canceled)

Thanks


回答1:


This explains how to use jQuery to do an ajax call and how to abort it. All you need to do is create an array that stores each request. You could then cancel the previous request while adding the new one.

ajaxRequests = new Array();

queueRequest = function() {
    if(ajaxRequests[ajaxRequests.length - 1]) {
        ajaxRequests[ajaxRequests.length - 1].abort();
    }

    ajaxRequests[ajaxRequests.length] = //Insert New jQuery AJAX call here.
}



回答2:


Since we only want the result of the last request, this is very simple and works.

var ajax = null;
var getFoo = function() {
    if(ajax) ajax.abort();
    ajax= $.ajax({});
};
getFool();
getFool();
getFool();
getFool();
getFool();
getFool();

only the last request is executed.




回答3:


Instead of using library, you can use Basic jquery Ajax method :

beforeSend:{}

For example:

xhr = jQuery.ajax({
            url: /*Your URL*/
            type: "POST",
            data: {
              //data
            },
             /* if there is a previous ajax request, then we abort it and then set xhr to null */
            beforeSend : function()    {           
                if(xhr != null) {
                    xhr.abort();
                }
            },
success:function(){}

});


来源:https://stackoverflow.com/questions/4176956/get-latest-ajax-request-and-abort-others

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!