在下面的AngularJS控制器中:
x
和y
$http.get()
执行AJAX调用,我从后端获得了正确的响应,并在变量x
和y
中保留了所需的响应值。 alert
消息中,我正在尝试打印x
和y
的值。我在Stack Overflow中经历了其他问题和答案,这是一个重复的问题,但在这里并不成功。
app.controller('MyController', function($scope, $http, $rootScope) {
$scope.x = '';
$scope.y = '';
$http.get('javaAngularJS').then(function (response) {
var data = response.data;
$scope.smsresult = data;
//need to print following x and y values in below alert message
$scope.x = $scope.smsresult.failure;
$scope.y = $scope.smsresult.success;
});
alert(x+" "+y);
});
但在警告消息中,x*
和y
的值未打印。上面的代码中我的错误是什么?
答案 0 :(得分:2)
尝试在响应函数中设置'x'和'y',如
$http.get('javaAngularJS').then(function (response)
{
var data = response.data;
$scope.smsresult = data;
//need to print following x and y values in below alert message
$scope.x = $scope.smsresult.failure;
$scope.y = $scope.smsresult.success;
alert($scope.x+" "+$scope.y);
});
Ajax调用是异步的,因此当您打印警报时,ajax尚未完成。
如果你想在成功块之外有处理逻辑,你可以将它放在单独的函数中并在成功部分调用它:
$http.get('javaAngularJS').then(function (response)
{
$scope.processSmsResponse(response);
});
$scope.processSmsResponse = function (response){
//your logic here
}
答案 1 :(得分:0)
你不应该使用$ scope.x / y吗?现在它们是未定义的变量x和y。
x = $scope.smsresult.failure;
y = $scope.smsresult.success;
到
$scope.x = $scope.smsresult.failure;
$scope.y = $scope.smsresult.success;
(我会评论,但没有业力)
答案 2 :(得分:-1)
app.controller('MyController', function($scope, $http, $rootScope)
{
$scope.x = '';
$scope.y = '';
$http.get('javaAngularJS')
.then(function (response)
{
var data = response.data;
$scope.smsresult = data;
//need to print following x and y values in below alert message
$scope.x = $scope.smsresult.failure;
$scope.y = $scope.smsresult.success;
});
alert($scope.x+" "+$scope.y);
});