jQuery global variable problem

前端 未结 6 804
伪装坚强ぢ
伪装坚强ぢ 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:09

    The AJAX function is asynchronous. It will run in the background and when it is done getting the ajax.php page it will run the success function.

    0 讨论(0)
  • 2021-01-22 11:10

    your if statement executes before your .ajax call completes

    0 讨论(0)
  • 2021-01-22 11:15

    Refactoring the code like this would work:

    function by_id() {
     if(id == 1) {   
       ... do something ...
     }
    }
    
    var id = $(this).children().html();
    $.ajax({
       url: 'ajax.php?id=' + id,
       success: function(data) {
          id = data;
          by_id();  // call on successful ajax load
       }
    });
    

    The advantage of wrapping your id logic in a function allows you to call it anywhere - be it at the end of an AJAX request, at page load, on a button press, etc.

    0 讨论(0)
  • 2021-01-22 11:18

    The A in Ajax is for Asynchronous. From within the 'success' callback you can call another function or execute post-ajax code.

    0 讨论(0)
  • 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
            ...
          }
       }
    });
    
    0 讨论(0)
  • 2021-01-22 11:25

    Hey a better solution is using the async: false property, something like this:

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

    ;)

    0 讨论(0)
提交回复
热议问题