2014-11-24 69 views
1

我有一个应该很难解决的问题,但我只是无法弄清楚我做错了什么。我通过$http请求收到dataAngularJS:从服务器读取响应数据

alert(data) 

给我object object

alert(data.response) 

给我{"id":"123456","post_id":"12345"}

alert (data.response.id) 

给我undefined

我的问题:我想要得到的ID。 为什么最后一个表达式给我定义的不是ID?我是否必须以某种方式转换数据?

我很感激任何提示!

+2

这意味着'data.response'是一个字符串,而不是一个对象在HTML文件显示它。否则,类似于alert(data)''你会得到'[object Object]'。 – dfsq 2014-11-24 22:03:55

+0

尝试_data.id_? – arman1991 2014-11-24 22:05:40

+2

你的回答可能是一个字符串。你需要先把它变成JSON。在$ scope.data.response上调用函数angular.fromJson,然后你可以调用这个id。 – AlvinJ 2014-11-24 22:09:25

回答

5

它看起来像你的data.response是一个字符串。 您使用angular.fromJson将其转换为对象,即:

$scope.temp = angular.fromJson($scope.data.response); 

请查看下面

var app = angular.module('app', []); 
 

 
app.controller('firstCtrl', function($scope){ 
 
$scope.data = { 
 
response:'{"id":"123456","post_id":"12345"}' 
 
}; 
 
    
 
    alert($scope.data); 
 
    alert($scope.data.response); 
 
    
 
    alert($scope.data.response.id); 
 
    
 
    $scope.temp = angular.fromJson($scope.data.response); 
 
    
 
    alert($scope.temp.id); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<body ng-app="app"> 
 
    <div ng-controller="firstCtrl"> 
 

 
     </div> 
 
</body>

+0

谢谢!完美的答案和完美的解释! – sebvst 2014-11-24 23:22:28

1
var app = angular.module('myApp', []); 

app.controller('list_employeesController', function($scope, $http) { 
    // email = $scope.email; 
    // psw = $scope.psw; 
    $http({ 
    method: "GET", 
    url: "http://localhost:3000/employees", 
    params: {} 

    }).then(function mySuccess(response) { 
     // a string, or an object, carrying the response from the server. 
     $scope.myRes = response.data; 
     $scope.statuscode = response.status; 

    }, function myError(response) { 
     $scope.myRes = response.statusText; 
    }); 
}); 

只要这里迈尔斯有响应数据这一请求工作演示。

而且我们可以用表达式语法在角

<h2> Result : {{myRes}} </h2>