【问题标题】:GET json data from a php file for an Angular scope从 Angular 范围的 php 文件中获取 json 数据
【发布时间】:2014-09-23 17:35:15
【问题描述】:

我正在尝试从 php 文件中获取 json 数据以在 Angular 控制器中使用。我在 php 文件中回显 json_encode(pg_fetch_assoc($result));,当我在角度控制器中 console.log($scope.contents); 时,它会带回 json 数据,但是当我尝试执行 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>

【问题讨论】:

    标签: javascript php json angularjs


    【解决方案1】:

    您需要实际以 JSON 格式发送数据。为此,您只需在echo 语句之前添加header('Content-Type: application/json');。所以 content.php 变成了:

    <?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', function ($scope, $http) {
        $http({method: 'GET', url: 'content.php'}).success(function(data) {
            $scope.contents = data;
        });
    });
    

    到这里:

    myApp.controller('ContentCtrl', ['$scope', '$http', function ($scope, $http) {
        $http.get('content.php')
        .success(function(data) {
            $scope.contents = data;
        });
    }]);
    

    函数定义前附加的'$scope', '$http',可以让你以后缩小,.get只是个人喜好,不过我觉得读起来更干净。

    【讨论】:

    • 感谢您的快速答复!
    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多