jQuery global variable problem

前端 未结 6 876
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 10:58
var id = $(this).children().html();  // id is 5
$.ajax({
   url: \'ajax.php?id=\' + id,
   success: function(data) {
      id = data;   // id is 1
   }
});
if(id == 1){          


        
6条回答
  •  醉酒成梦
    2021-01-22 11:23

    The $.ajax() function has to go and get the data, it hasn't done this and executed your success callback by the time it reached the code immediately after.

    Your code order actually happens like this:

    var id = $(this).children().html();
    //Ajax start
    if(id == 1){ }
    //Ajax end (sometime later, not immediately after)
    function(data) { id = data; }
    

    If you are depending on this value to continue, stick it in the success callback:

    var id = $(this).children().html();  // id is 5
    $.ajax({
       url: 'ajax.php?id=' + id,
       success: function(data) {
          id = data;   // id is 1
          if(id == 1){    // id is now 1
            ...
          }
       }
    });
    

提交回复
热议问题