2014-11-24 40 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>