$http.get("./data/web.json")
请求成功,返回一个数组。当我通过请求循环数组时,迭代器变量 i
将是未定义的?!那么如何访问返回数组并执行循环请求呢?
<script>
var ngApp = angular.module("webApp", ['xml'])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('xmlHttpInterceptor');
})
.controller("webCtrl", function($scope, $http) {
$http.get("./data/web.json")
.success(function(response) {
$scope.websites = response;
for (i = 0; i < $scope.websites.length; i++){
$http.get('../api/alexa?url=' + $scope.websites[i].url)
.success(function(rsp) {
//$scope.websites[i].rank = rsp.data.POPULARITY.TEXT;
console.log($scope.websites[i]);
});
}
console.log(response);
});
});
</script>
最佳答案
.controller("webCtrl", function ($scope, $http) {
$http.get("./data/web.json")
.success(function (response) {
$scope.websites = response;
for (i = 0; i < $scope.websites.length; i++) {
$scope.processWebsites($scope.websites[i], i);
}
});
$scope.processWebsites = function (website, index) {
$http.get('../api/alexa?url=' + website.url)
.success(function (rsp) {
console.log($scope.websites[index]);
});
}
});
试试这段代码。这将创建一个新的执行上下文,从而消除由于异步执行而产生的任何意外副作用。
关于javascript - Angular 循环请求未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34393166/