我有一个运行ajax调用的简单控制器。每15秒运行一次这个ajax调用的最佳选择是什么,而不只是一次。我怎么也停止通话?
myApp.controller('myCntrl', function($window,$scope,$http,$routeParams,$location) {
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
console.log(data)
})
})
答案 0 :(得分:4)
function httpCall (){
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
if(data == "expectedData") //condition to stop recursive ajax.
$tiemout(httpCall, 15000);
})
}
答案 1 :(得分:3)
您可以使用$interval
服务,并在cancel(promise)
例如:
var promo = $interval(function(){
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
console.log(data)
})
},1500);
清除间隔为:
$interval.cancel(promo)
答案 2 :(得分:1)
您只需使用$interval
var ajaxCall = function(){
$http({
method: 'GET',
url: '../ajax/my_script.php',
})
.success(function(data, status, headers, config) {
//on some condition
if(data.length == 0) //just for demonstration..you could add your own condition.
$interval.cancel(interval); //this is to cancel interval
console.log(data)
})
}
var interval = $interval(ajaxCall,15000)