【问题标题】:Handling AJAX in nested loop (Angularjs) [duplicate]在嵌套循环(Angularjs)中处理 AJAX [重复]
【发布时间】:2015-03-18 08:12:35
【问题描述】:
var    $scope.units = [1,2];
var  $scope.shiftplans = ['plan1','plan2','plan3']

         for(var i=0;i<$scope.units.length;i++){            
          for(var a=0;a<$scope.shiftplans.length;a++)  {
            console.log('i:'+i);
            console.log('a:'+a);
         } 
        }

打印:

i:0
a:0

i:0
a:1

i:0
a:2

i:1
a:0

i:1
a:1

i:1
a:2

但是:

var    $scope.units = [1,2];
    var  $scope.shiftplans = ['plan1','plan2','plan3']

  for(var i=0;i<$scope.units.length;i++){            
     for(var a=0;a<$scope.shiftplans.length;a++)  {
       ***$http.get(function(){
               console.log('i:'+i);
               console.log('a:'+a);
       });***

     } 
 }

上面ajax的控制台登录根据ajax响应打印出不同的值。

如何处理 AJAX 来完成和稍后移动到循环?

【问题讨论】:

  • 这是什么意思:“如何处理AJAX来完成和稍后移动到循环”
  • @Satpal 是的,所以请确保使用大量的 XML。 ;-P
  • 不清楚你在问什么
  • 是的@JLRishe,这就是我想要的(即)我将根据嵌套循环数据将输入传递给该 ajax 调用。因此,对于每次迭代,数据都会根据循环发生变化。但在我当前的场景中,循环在我的 ajax 响应之前完成。

标签: javascript ajax angularjs promise


【解决方案1】:

对于每个 ajax 调用,您需要在 IIFE 上绑定 i 和 a 的值,因为 ajax 调用是异步的,与 for 循环不同

示例:

for(var i=0;i<$scope.units.length;i++){            
 for(var a=0;a<$scope.shiftplans.length;a++)  {
       (function(_i, _a) {
           ***$http.get(function(){
                 console.log('i:'+_i);
                 console.log('a:'+_a);
           });***
       })(i, a);
     } 
 }

【讨论】:

    【解决方案2】:

    由于是异步调用,无法处理何时会收到回调AngularJs: $http Synchronous call

    我能想到的唯一方法是创建一个对象数组并将响应映射到正确的键。在收到所有响应后,它可以打印出数组。像这样的:

    var $scope.units = [1,2];
    var $scope.shiftplans = ['plan1','plan2','plan3'];
    
    var sizeOfResponses = $scope.units.length * $scope.shiftplans.length;
    var countOfResponses = 0;
    var responsesArray = [];
    
    for(var i=0;i<$scope.units.length;i++){            
      for(var a=0;a<$scope.shiftplans.length;a++)  {
        var index = i * $scope.units.length + a;
        responsesArray[index] = {i: null, a: null
        $http.get(function(){
          responsesArray[index].i = +i;
          responsesArray[index].a = +a;
          countOfResponses++;
          if(countOfResponses === sizeOfResponses)console.log(responsesArray);
       });
    
     } 
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2017-07-24
      • 2011-05-19
      • 2016-01-11
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      相关资源
      最近更新 更多