jQuery 变量更改值并发出警报

jQuery variable changes value with alert

我正在设置一个名为 flag_done 的标志,我用它来确保在逐行更新我的数据库记录时没有错误。如果没有错误,我将重置数据库。

更新工作正常,flag_done 变量显示 2 个不同的值和 2 个连续的相同警报。

我错过了什么?

var flag_done = "initial";
function updateDatabase(){
  UpdateList = JSON.parse(localStorage["UpdateList"]);  // get it from local
  if (UpdateList.length > 0 ){
    for (i = 0; i < UpdateList.length; i++) {
      set_url = "checks/"+UpdateList[i].id+".json";
      $.ajax({
        type: "PUT",
        url: set_url,
        data: JSON.stringify(UpdateList[i]),
        contentType: 'application/json', // format of request payload
        dataType: 'json', // format of the response
        success: function(msg) {
          // flag_done = "success";  // this actually worked but the same issue as error, the initial value shows up first when alerting twice!
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("OFFLINE!");
          flag_done = "error";  // This sets correctly
          alert("flag_done should be error: "+flag_done);  // Shows as error (correct)
        }
      } )
      alert("still inside for loop: "+flag_done);     // This shows initial and not error - ever!     
    }

    alert("flag_done: "+ flag_done); // shows initial
    alert("flag_done: "+ flag_done); // shows error!!

    if ( flag_done == "error" ) {
      alert("Couldn't SYNC right now, saved offline.");
    }else{
      alert("Updated OK");
      // resetDatabase();
    }
  } 
};

您需要将其作为请求数组进行管理

var theBigOne = [];

for (i = 0; i < UpdateList.length; i++) {
     var currentReq = $.ajax({........});
     theBigOne.push(currentReq);
}

$.when.apply($, theBigOne).then(function(results) {
     console.log(results);
}, 
function(e) {
     console.log("Something failed");
});

在这种情况下,您的警报垃圾邮件不会让您看到真正的 ajax 执行过程(那是异步的)....它是一种同步伪装