javascript - Jquery - 按顺序循环ajax

标签 javascript jquery ajax

所以我有一系列需要更新的东西,但由于 async:false 已被弃用,它需要一个一个地显示更新进度,有什么方法可以用 ajax.success 做到这一点, 例子:

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

我尝试将 progressUpdate() 放在 success 中,但不是按照数组的顺序,因为它在收到回调时更新,一些后元素在前一个元素之前完成,就像这样

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

有什么办法可以按顺序进行这个进程吗?

最佳答案

这个呢?

do_job(stuff, 0); // Launch first job

function do_job(stuff, index) {
  if (index < stuff.length)
  {
    $.ajax({
      type: "PUT",
      global: true,
      url: '/stuffs/'+stuff[f].id+'.json',
      contentType: 'application/json', 
      dataType: 'script', 
      data: JSON.stringify({stuff:{set: 1}, _method:'put'}),
      success: function(data) {
        // Job finished, let's begin the next one
        progressUpdate(stuff[index].name, 100 / stuff.length)   
        do_job(stuff, index + 1); // actual index (your variable "f") + 1
      }
    });
  } else {
    // every stuff is finished
  }
}

关于javascript - Jquery - 按顺序循环ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35328474/

相关文章:

jquery - ajax post 请求是请求的资源上不存在 'Access-Control-Allow-Origin' header 。

php - 对 Ajax 脚本的任何更改都会产生 Uncaught TypeError

javascript - VSCode 智能感知无法从 JSDoc 检测对象类型

javascript - react 阻止关注点击

javascript - 为什么 location.hash 上的输出不自动刷新?

javascript - 如何使 "roll-up curtain"样式的下拉菜单在卷起时不会在其父项上方弹出

javascript - 使用 HTML5 和 javascript 在后台顺序或随机播放多个音频文件

javascript - 从数组中返回排序后的唯一值,但如果计数相等,则按顺序返回值

javascript - 用图层覆盖整个页面

c# - pagedList中如何使用ajax