在触发一系列ajax请求时对它们进行排队

Queuing a series of ajax requests as they are triggered

本文关键字:排队 一系列 ajax 请求      更新时间:2023-09-26

我希望使用JQuery将一系列AJAX请求排队。假设有一个updateImage()函数,它根据用户单击的按钮向服务器查询URL,并返回指向图像的链接。服务器记录imageId,浏览器显示图像。这个应用程序要求成功回调函数的顺序按照它们被发送的顺序来触发(以便浏览器显示与用户的点击顺序相对应的图像)。

游戏介绍:

//User a number of buttons in quick succession
$(".button").click(function(){
    var imageId = $(this).attr("id");
    updateImage(imageId);               
});
//Ajax success callbacks need to run in the order of the clicks
function updateImage(imageId) {
    $.ajax({
    url: /someurl,
    data: imageId,
    success: successFunction    //this function will update the DOM
  });
}

我考虑过$。ajaxStop,但问题是,还有其他AJAX函数,我不想被停止或排队,因为这个updateImage函数。我还研究了美元。,但这允许您链接已知数量的ajax调用执行,但我不确定用户会点击多少次-我不确定这是否适用于这里。

这就达到了您想要的效果。基本上,下面的代码正是您想要的,一个带有异步ajax请求的同步事件队列。一定要在updateImage函数中填上你成功后需要做的事情。

编辑11/12/2015

@ _beng在推特上指出我的原始版本是pyramid of doom。他是对的,因为队列有可能发生变异导致索引不一致的问题(在单击事件处理程序触发时数组更改长度);导致在点击处理程序/ajax回调中使用时索引发生变化)一种简单的补救方法是将队列复制到一个临时变量中并对其进行处理,只进行截断在不发生变异的情况下安全排队。我试图涵盖所有我能想到的边缘情况,但可能有一些我遗漏了。无论如何,快乐的编码。如果出现问题,您可能希望使用悲观锁定,如果您能弄清楚如何在javascript中实现它。我试过很多次,都失败了。
$(function(){
    var queue = [],
    var q = {},
    var t;
    $(".button").click(function(){
        var index = queue.push({
            id: imageId,
            completed: false
        });
        $.ajax({
            url: /someurl,
            data: imageId,
            success: function(data){
                //since length is 1 based and index is 0 based
                //queue.length > index ~ queue.length >= index+1
                if(queue.length > index){
                    queue[index].completed = true;
                    $(q).trigger('completed');  
                }
            }
        });
    });
    $(q).on('completed',function(){
        if(typeof t === 'number') clearTimeout(t);
        //copy queue to a temporary array.
        var copy = (function(){ return queue.slice(); }());//for the paranoid perform safe "copy" of array
        var copy_len = copy.length;//starting copy length
        t = setTimeout(function(){
            while(copy.length > 0){
                if(copy[0].completed == false) break;
                var item = copy.shift();
                updateImage(item.id);
            }
            //if queue length has changed,we could mistakenly delete unprocessed items by truncating array
            //only destroy queue if copy.length === 0 and queue.length equals starting copy length
            if(copy.length===0 &&copy_len===queue.length){
                queue.length = 0; //truncate queue only when it is "safe"
            }
        },100);

    });
    function updateImage(imageId)
    {
        //do whatever you need to do here on completion.
    }
});