jQuery变量通过alert更改值

时间:2015-07-28 14:58:35

标签: javascript jquery offline

我设置了一个名为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();
    }
  } 
};

1 个答案:

答案 0 :(得分:1)

You need to manage this as an array of request

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

your spam of alert don't make you see the real ajax execution process in this case ( thats asynchronous ).... its a sort of syncro camouflage