我试图调用一个函数,通过链接从servlet返回一个json对象。
我的HTML链接,调用fTest函数:
<td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descarga)">ver</a></td>
我的控制器:
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {$scope.descargas = response.descargas;});
$window.alert(JSON.stringify($scope.descargas));
};
});
当我第一次按下时,链接出现&#34;未定义&#34;在警报
但是当我第二次按下时,如果我能看到在警报中返回的json对象
首次按链接时可能会发生什么?请帮忙
感谢
答案 0 :(得分:0)
这里的问题是你在成功回调之外警告$ scope.descargas因此它确实没有定义但是尝试像这样修改它。
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
$window.alert(JSON.stringify($scope.descargas));
});
};
});
答案 1 :(得分:0)
由于在Angular中使用$ http的每个服务器端请求都是AJAX,即对服务器的异步调用,因此假设在成功响应执行完成后将调用您的警报方法。但这是错误的。
这是承诺的概念来自Angular。
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga) {
console.log("1");
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
console.log("2");
});
console.log("3");
$window.alert(JSON.stringify($scope.descargas));
};
});
因此,当您在服务器端执行此代码延迟时,您会看到控制台日志的顺序为: 1 , 3 和 2 强>
因此,当从服务器收到响应时,将执行您的成功函数。因此,descargas
变量中的值第一次为空,但使用第一个服务器响应存储,下次显示上次调用的值。