Json AngularJS:从服务器读取响应数据
我有一个问题需要解决,但我就是不知道我做错了什么。我通过Json AngularJS:从服务器读取响应数据,json,angularjs,Json,Angularjs,我有一个问题需要解决,但我就是不知道我做错了什么。我通过$http请求接收数据 alert(data) 给我对象对象 alert(data.response) 给我{“id”:“123456”,“post_id”:“12345”} 给我未定义的 我的问题:我想得到ID。为什么最后一个表达式给我的是未定义的ID而不是ID?我必须以某种方式转换数据吗 我很感谢你给我的任何提示 看起来像是您的数据。响应是一个字符串。 您可以使用angular.fromJson将其转换为对象ie: $scope.t
$http
请求接收数据
alert(data)
给我对象对象
alert(data.response)
给我{“id”:“123456”,“post_id”:“12345”}
给我未定义的
我的问题:我想得到ID。为什么最后一个表达式给我的是未定义的ID而不是ID?我必须以某种方式转换数据吗
我很感谢你给我的任何提示 看起来像是您的数据。响应是一个字符串。
您可以使用angular.fromJson
将其转换为对象ie:
$scope.temp = angular.fromJson($scope.data.response);
请参阅下面的工作演示
var-app=angular.module('app',[]);
app.controller('firstCtrl',函数($scope){
$scope.data={
答复:“{”id:“123456”,“post_id:“12345”}”
};
警报($scope.data);
警报($scope.data.response);
警报($scope.data.response.id);
$scope.temp=angular.fromJson($scope.data.response);
警报($scope.temp.id);
});代码>
在这里,myRes拥有对该请求的响应数据
我们可以在HTML文件中使用表达式语法以角度显示它
<h2> Result : {{myRes}} </h2>
Result:{{myRes}
这意味着data.response
是一个字符串,而不是一个对象。否则类似于警报(数据)
您将得到[object object]
。您的响应可能是一个字符串。首先需要将其转换为JSON。在$scope.data.response上调用angular.fromJson函数,然后可以调用id。谢谢!完美的答案和完美的解释!
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>
var app = angular.module('myApp', []);
app.controller('student_Controller', function($scope, $http) {
$http({
method: "GET",
url: "http://localhost:8000/employees",
}).then(function mySuccess(response) {
$scope.res= response.data;
$scope.statuscode = response.status;
}, function myError(response) {
console.log("response--"+response);
});
});