一个回调多个JSON请求多个、回调、JSON

2023-09-10 20:16:57 作者:人生如流水

我想在jQuery的Ajax请求第X号并添加JSON响应到一个数组。 当所有Ajax请求都做了,我想执行一些code。有没有解决这个好办法?

I want to make X number of ajax requests in jQuery and add the json response to an array. When all the ajax requests are done, I would like to execute some code. Is there a good way to solve this?

推荐答案

这code应该做你想做的,所有的jQuery的风格。基本上它使用的这一切有点递归。选项​​传递给loadmultiples功能,您想做什么设置,和JSON响应推到一个数组。你可以很容易地改变它,如果你不是想的JSON响应合并成一个单一的结构,但我不知道如果这是你想要的。

This code should do what you want, all jQuery style. Basically it uses a bit of recursion to get it done. Pass options to the loadmultiples function to set up what you want to do, and JSON responses are pushed onto an array. You could easily change it if you instead wanted to merge the JSON responses into a single structure, but I wasn't sure if that was what you wanted.

var loadmultiples = function(options) {    

    var settings = $.extend({

        //set the url to get
        url : '/response.json',

        //this function is called when everything is done
        callback : function() {},

        //set this option to define how many loads to do
        numbertodo : 10,

        //these two are just used for
        //storing data while we recurse,
        //and keeping track of the current position
        //however you can change them if you want to start
        //from a different point, or have existing data
        numberdone : 0,
        data : []
    }, options || {});

    //load the json, passing up the current 'number'
    //of the content to load
    $.ajax({
        url : settings.url,
        data : { 'number' : settings.numberdone },
        dataType: 'json',        
        success: function(result) {            

            //add the response to the data
            settings.data.push(result);

            //increment the counter of how many files have been done
            settings.numberdone++;

            //
            if(settings.numberdone < settings.numbertoexecute) {
                loadmultiples(settings);
            } else {
                settings.callback(settings.data);
            }

        }        
    });

}

//so now we can call it...
loadmultiples({
    callback: function(data) {
        //this function will get called when all the data calls have been
        //completed, and the resulting data is in the data parameter

    }
});