Ren*_*unt 2 ajax jquery 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;
});
};
})
Run Code Online (Sandbox Code Playgroud)
这是工作找到get_info ajax每5秒发送一次.但是当我触发set_info ajax然后get_info ajax正在触发时它正在等待完成set_info ajax.
我想在get_info fire然后不等待的时候同时处理两个链接,直到set_info ajax结束.
谢谢.
nwa*_*yve 21
我想你感兴趣的是$q.all.从文档:
所有的(承诺);
将多个promise组合成一个promise,在解析所有输入promise时解析.
参数
Param | Type | Details
promises | Array.<Promise> Object.<Promise> | //An array or hash of promises
Run Code Online (Sandbox Code Playgroud)
返回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;
});
Run Code Online (Sandbox Code Playgroud)
这是一个在行动的吸收者.
在重新阅读了这个问题之后,我意识到异步制作两个ajax请求,同时只想对两者进行单个回调,这不是原始问题的问题.
根据我的理解,问题是询问如何同时发生多个ajax请求,而不考虑首先发生的事件,并且不需要共同解决的promise回调(作为我的原始答案地址).
当发出ajax请求(例如$http.get(...);)时,javascript的执行不会停止.如果发出了另一个ajax请求,无论第一个是否完成,它都会触发.在间隔循环中持续发生ajax请求并且触发按钮事件时,独立的ajax请求不应导致任何冲突.
虽然问题中的代码并不理想,但我无法确切地知道为什么'get_info'请求正在等待'set_info'请求完成.我已经创建了一个jsFiddle来尝试重新创建原始代码的功能,它似乎按预期工作:
我使用jsFiddle,因为它有一个/echo/json/api功能来测试ajax功能.如果您将开发人员工具打开到控制台,这个小提琴将记录ajax请求的关键点.$ timeout包装器每5秒触发一次,我将GetDataajax的响应设置为延迟6秒.在控制台中记录getEventSeconds函数时,单击GetDataajax按钮.它将记录它开始,然后getEventSeconds将再次记录,最后GetDataajax将得到解决.
在旁注中,我不得不使用jQuery的$ .ajax()而不是Angular的$ http,因为出于某种原因,尽管使用了请求标头(Content-Type),$ http帖子对jsFiddle的echo服务并不好用. .请求"有效",但延迟功能不会.