同时ajax请求angularjs?

时间:2014-07-17 04:04:19

标签: jquery ajax angularjs

我想一次发送multipal ajax请求。这是我的js代码。

<a class='btn btn-success' ng-click='getDataajax()'>Re Check</a>

app.controller('customersCrtl', function($scope, $http, $timeout) {
    function wrapper() {
        $scope.getEventSeconds();
        $timeout(wrapper, 5000);
    }
    $http.get('cget.php', {
        params: {
            'action': 'get_info'
        }
    }).success(function(data) {
        $scope.list = data;
        $scope.currentPage = 1; //current page
        $scope.entryLimit = 10; //max no of items to display in a page
        $scope.filteredItems = $scope.list.length; //Initially for no filter  
        $scope.totalItems = $scope.list.length;
    });
    $timeout(wrapper, 5000);
    $scope.getDataajax = function() {
        $http.get('cget.php', {
            params: {
                'action': 'set_info'
            }
        }).success(function(data) {});
    };
    $scope.getEventSeconds = function() {
        $http.get('cget.php', {
            params: {
                'action': 'get_info'
            }
        }).success(function(data) {
            $scope.list = data;
            $scope.currentPage = 1; //current page
            $scope.entryLimit = 10; //max no of items to display in a page
            $scope.filteredItems = $scope.list.length; //Initially for no filter  
            $scope.totalItems = $scope.list.length;
        });
    };
})

这是工作查找get_info ajax每5秒发送一次。但是当我触发set_info ajax然后get_info ajax正在触发时它正在等待完成set_info ajax。

我想在get_info fire然后不等待的时候同时处理两个链接,直到set_info ajax结束。

谢谢。

2 个答案:

答案 0 :(得分:21)

我认为您感兴趣的是$q.all。来自文档:


  

所有(许诺);

     

将多个承诺合并到一个承诺中,该承诺在所有输入承诺得到解决后解析   参数

Param    | Type                             | Details
promises | Array.<Promise> Object.<Promise> | //An array or hash of promises

返回将使用值的数组/散列解析的单个Promise,每个值对应于promises数组/散列中相同索引/键的promise。如果任何承诺通过拒绝得到解决,则此结果承诺将被拒绝并具有相同的拒绝价值。


实施例

$q.all({
  users: $http.get('https://api.github.com/users'),
  repos: $http.get('https://api.github.com/repositories')
}).then(function(results) {
  var users = results.users.data;
  var repos = results.repos.data;
});

这里有plunker这个。

更新

在重新阅读了这个问题之后,我意识到异步制作两个ajax请求,同时只想对两者进行一次回调,这不是原始问题的问题。

根据我的理解,问题是询问如何同时发生多个ajax请求,而不考虑首先发生的事件,并且不需要共同解决的promise回调(作为我的原始答案地址)。

当发出ajax请求时(例如$http.get(...);),javascript的执行不会停止。如果发出另一个ajax请求,无论第一个是否完成,它都会触发。在间隔循环中持续发生ajax请求并触发一个按钮事件独立的ajax请求不应该导致任何冲突。

虽然问题中的代码并不理想,但我无法理解为什么&#39; get_info&#39;请求正在等待&#39; set_info&#39;要求完成。我创建了一个jsFiddle来尝试重新创建原始代码的功能,它似乎按预期工作:

http://jsfiddle.net/Tnt56/

我使用了jsFiddle,因为它具有/echo/json/ api功能来测试ajax功能。如果您将开发人员工具打开到控制台,这个小提琴将记录ajax请求的关键点。 $ timeout包装器每5秒触发一次,我将GetDataajax的响应设置为延迟6秒。在控制台中记录getEventSeconds函数时,单击GetDataajax按钮。它将记录它已启动,然后getEventSeconds将再次记录,最后GetDataajax将得到解决。

另一方面,我不得不使用jQuery的$ .ajax()而不是Angular的$ http,因为出于某种原因,$ http的帖子并不适合用jsFiddle&# 39; s echo服务,尽管使用了请求标头(Content-Type)。请求&#39;工作&#39;但延迟功能不会。

答案 1 :(得分:1)

我重写了你的控制器以使用闭包来使每个调用异步并保持干燥。

我对此进行了测试并且有效,请在此处查看:http://jsfiddle.net/s6uFx/2/

app.controller('customersCtrl', function ($scope, $http, $timeout) {
  function cget(action) {
    return $http.get('cget.php', {params: {action: action}});
  }

  $scope.getDataajax = function () {
    cget('set_info')
    .success(function (res) {
        console.log(JSON.stringify(res));
    });
  };

  $scope.getEventSeconds = function () {
    cget('get_info')
    .success(function (res) {
      console.log(JSON.stringify(res));
      $scope.list = res;
      $scope.currentPage = 1; //current page
      $scope.entryLimit = 10; //max no of items to display in a page
      $scope.filteredItems = $scope.list.length; //Initially for no filter
      $scope.totalItems = $scope.list.length;
    })
    .then(function () {
      // and start to loop
      $timeout($scope.getEventSeconds, 5000);
    });
  };

  // this call replaces the first $http.get and starts the loop
  $scope.getEventSeconds();
});
相关问题