jQuery getting rid of nested ajax functions

前端 未结 2 1464
臣服心动
臣服心动 2021-01-07 13:17

In my JS, I need to get the contents of 3 files with AJAX, then do some code. This has led to a rather strange looking creation of nested async functions. Also anytime I\'m

2条回答
  •  梦谈多话
    2021-01-07 13:50

    Create an array of each needed file, then loop through the array of files and call $.get each iteration, and have it call a combining function that will combine the data and do a count check, once count is reached call callback.

    function loadData(files,callback){
        var combinedData = "";
        var count = 0;
        function combineFile(data){
           count++;
           combinedData += data;
           if(count==files.length-1){
              callback(combinedData);
           }
        }
    
        for(var i=0; i

提交回复
热议问题