我正在尝试从php文件中获取json数据,以在Angular控制器中使用。我json_encode(pg_fetch_assoc($result));在php文件中回显,当我console.log($scope.contents);在角度控制器中时,它带回json数据,但是当我尝试做一个ng- repeat
json_encode(pg_fetch_assoc($result));
console.log($scope.contents);
ng- repeat
controllers.js :
myApp.controller('ContentCtrl', function ($scope, $http) { $http({method: 'GET', url: 'content.php'}).success(function(data) { $scope.contents = data; }); });
content.php :
<?php require_once("sdb.php"); $result = pg_query($dbconn, "SELECT * FROM content ORDER BY name ASC"); echo json_encode(pg_fetch_assoc($result));
index.php :
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="css/style.css"/> </head> <body ng-app="myApp"> <div ng-controller="ContentCtrl"> <ul> <li ng-repeat="content in contents"> <a href="#">{{content.name}}</a> </li> </ul> </div> </body> <script src="js/jquery-1.10.2.js"></script> <script src="js/angular.min.js"></script> <script src="js/controllers.js"></script> </html>
您实际上希望将数据作为JSON发送。为此,您只需要header('Content-Type: application/json');在echo语句之前添加即可。因此content.php变为:
header('Content-Type: application/json');
echo
<?php require_once("sdb.php"); $result = pg_query($dbconn, "SELECT * FROM content ORDER BY name ASC"); header('Content-Type: application/json'); echo json_encode(pg_fetch_assoc($result));
顺便说一句,您可能需要对控制器做一些事情。我会改变这个:
对此:
myApp.controller('ContentCtrl', ['$scope', '$http', function ($scope, $http) { $http.get('content.php') .success(function(data) { $scope.contents = data; }); }]);
'$scope', '$http',函数定义之前的附加内容使您将来可以精简,并且这.get只是个人喜好,但我认为阅读起来更简洁。
'$scope', '$http',
.get