weixin_33709364 2016-02-11 00:08 采纳率: 0%
浏览 126

jQuery-按顺序循环执行Ajax

So i have this array of stuff that it needs to be updated, but since async:false was deprecated and it needs to be one by one to show the progress of the update, is any way to do this with ajax.success?, example:

progressUpdate(stuff[0].name, 100 / stuff.length)
for(var f = 0; f < stuff.length; f++){

  $.ajax({
    type: "PUT",
    global: true,
    url: '/stuffs/'+stuff[f].id+'.json',
    contentType: 'application/json', 
    dataType: 'script', 
    data: JSON.stringify({stuff:{set: 1}, _method:'put'})
  });


  //Wait here to finish updating, then continue increase the progressbar

  progressUpdate(stuff[f].name, 100 / stuff.length)     
}

I try to put the progressUpdate() inside the success but is not in the order of the array, since it updates when it recives the callback, some of the posterior elements finish before the previous element, like this

....
.success: funcion(){
  progressUpdate(stuff[f].name, 100 / stuff.length)
}
....

Is there any way to do this progression in order?

  • 写回答

2条回答 默认 最新

  • weixin_33709219 2016-02-11 00:20
    关注

    One way to make it update the stuff in order would be to call for the next update only on the success of the previous. Something like this

    function updateStuff(f){
       if(f < stuff.length){
          ajax stuff ...
          success: funcion(){
             progressUpdate(stuff[f].name, 100 / stuff.length)
             updateStuff(f+1);
          }
       }
    }
    

    And call updateStuff(0) to start the recursion.

    评论

报告相同问题?