Javascript Angularjs显示ajax响应
基本上我的角度代码是这样的Javascript Angularjs显示ajax响应,javascript,jquery,angularjs,ajax,Javascript,Jquery,Angularjs,Ajax,基本上我的角度代码是这样的 var myapp = angular.module("Demo",["ngRoute"]) .config(function($routeProvider){ $routeProvider .when("/students",{
var myapp = angular.module("Demo",["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when("/students",{
templateUrl : "templates/students.html",
controller : "grouplistcontroller"
})
})
.controller("grouplistcontroller", function($scope,$http){
$http.get("ajaxfunction.php?action=getlist")
.then(function(res) {
var obj = JSON.stringify(res);
console.log(obj);
$scope.students = obj.data;
});
});
来自服务器的json数据如下所示
"data":[
{
"sub_id":"1199",
"sub_group":"GT"
},
{
"sub_id":"727",
"sub_group":"GT"
},
{
"sub_id":"660",
"sub_group":"GT"
},
{
"sub_id":"614",
"sub_group":"GT"
}
],
"status":200,
"config":{
"method":"GET",
"transformRequest":[
null
],
"transformResponse":[
null
],
"url":"ajaxfunction.php?action=getlist",
"headers":{
"Accept":"application/json, text/plain, */*"
}
},
"statusText":"OK"
我试图在我的前端显示结果中的循环,但它不起作用
<ul>
<li ng-repeat="student in students">
{{ student.sub_id }}
</li>
</ul>
-
{{student.sub_id}
我认为控制器无法从服务器获取数据。
控制器不适用于此。您应该使用服务来查看此代码。我希望这可能对你有用
<body ng-app="Demo">
<div ng-controller="grouplistcontroller">
<ul>
<li ng-repeat="student in students">
{{ student.sub_id }}
</li>
</ul>
</div>
</body>
控制器:
myapp.controller("grouplistcontroller", ['$scope', 'SampleService', function($scope, SampleService) {
function suuccessMethod(res) {
$scope.students = res.data;
}
function errorMethod(err) {
}
SampleService.get().then(suuccessMethod, errorMethod);
}]);
服务:
myapp.factory('SampleService', function($http) {
return {
get: function() {
return $http.get("ajaxfunction.php?action=getlist");
}
}
});
您的问题:本次活动的问题:
function suuccessMethod(res) {
$scope.students = res.data;
}
如上所述,我希望它能工作您好,您不必转换JSON.stringify(obj),只需将其用作对象即可。。。使用下面的控制器
.controller("grouplistcontroller", function($scope,$http){
$http.get("ajaxfunction.php?action=getlist")
.then(function(res) {
$scope.students = res.data;
});
});
定义“不工作”不工作将重定向到ng repeat或json数据,试图找出它在哪里,如果您有输入错误。它应该是
$scope.students=res.data
,而不是obj.data
obj
是您的JSON字符串,它没有数据
属性。明白为什么要将其转换为字符串吗?在这种形式下,您无法访问对象的属性。“您应该使用服务”是的,这是服务对不起,我没有收到您的问题?为什么要创建一个服务(SampleService
)来包装另一个服务($http
)没有添加任何内容吗?我没有太大的理由这样做,但我认为在我们的应用程序中,这样做是可读的。我认为,所有服务器通信调用都可以封装在单个服务中,这样对usDebugging来说也很容易阅读。不会吧??如果我错了,请纠正我
.controller("grouplistcontroller", function($scope,$http){
$http.get("ajaxfunction.php?action=getlist")
.then(function(res) {
$scope.students = res.data;
});
});