获取最新的 ajax 请求并中止其他请求

2022-01-21 00:00:00 queue jquery javascript html ajax

我一直在寻找,这个问题看起来很简单,但找不到答案.我有多个请求调用不同的 url.但是对于每个 url,我只想要一次结果,并且它必须是被调用的同一个 url 中的最后一个.我现在的问题是如何只获得最后一个?"我看了这个好像3岁了:

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

(getuserprofile队列中现有的ajax将被取消)

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

谢谢

推荐答案

这个解释 如何使用 jQuery 进行 ajax 调用以及如何中止它.您需要做的就是创建一个存储每个请求的数组.然后,您可以在添加新请求的同时取消之前的请求.

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.
}

相关文章