Deferred and Ajax

后端 未结 3 884
生来不讨喜
生来不讨喜 2021-02-06 06:33

Reading a JSON-Service like this:

$.ajax({
  url:\'activeIDs\',
  success : function(data){ // data = [14,15]
    var tableRows = [];
    for (var dataIndex=0; d         


        
3条回答
  •  时光说笑
    2021-02-06 06:56

    You'll need to wait for all requests to finish before alerting.

    $.ajax({
      url:'activeIDs',
      success : function(data){ // data = [14,15]
        var tableRows = [];
        var requests = [];
        for (var dataIndex=0; dataIndex < data.length; dataIndex++) {
          var isLast = dataIndex == data.length;
    
          var request = $.ajax({
            url: 'info?id=' + data[dataIndex]
          }).done(function(data2) { // "foo", "bar"
            tableRows.push(data2.name);
          });
    
          requests.push(request);
        }
    
        // wait for all requests to finish here
        $.when(requests).then(function(){
          // all success functions have been called and updated things appropriately
          alert(tableRows.length);
        }
      }
    });
    

    This assumes that all requests succeed. It also looks like there are a few typos

    • Where does tableRows get updated?
    • Where is entries defined?

    Edit Now using promise style success handler. Should push the result in to tableRows before calling the $.when().then callback

提交回复
热议问题