在angularjs中处理json响应(来自PHP和mysql)


Handle json response (from PHP and mysql) in angularjs

从php获取Json响应时遇到问题。我正在使用AngularJs来显示收到的Json数据。我是刚接触棱角分明的人,先尝试了一个简单的练习。请帮忙。提前谢谢。

index.html

<!DOCTYPE HTML>
<html ng-app="app">
<head>
   <title>PHP MySQL API Consumed with AngularJS</title>
</head>
<body>
     <div ng-controller="GetUsers">
    <table border="1">
       <thead><tr><th>ID</th><th>Name</th><th>City</th></tr></thead>
       <tbody>
          <tr ng-repeat="user in users"><td>{{user.user_id}}</td><td>  {{user.first_name }}</td><td>{{user.user_city}}</td></tr>
       </tbody>
       </tfoot></tfoot>
    </table>
</div>
 <script>
    var app = angular.module('app', []);
    app.controller('GetUsers', function ($scope,$http){
        $http.get('http://localhost/angmysql/api.php').success(function(data) {
            $scope.users = data;
        });
      }
   });
  </script>
<script src="angular.js"></script>
<body>
</html>

api.php

<?php
    $db_name  = 'dbtuts';
    $hostname = 'localhost';
    $username = 'root';
    $password = '';
    $dbc = mysqli_connect('localhost','root','','dbtuts') or die('Error connecting to database');
    $sql = mysqli_query($dbc,"SELECT * FROM users");
    $emparray = array();
    while($row =mysqli_fetch_assoc($sql))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);
    mysqli_close($dbc);
?>

$http传递给回调的参数是一个对象,其中响应体存储在.data字段中。

试试这个:

$http.get('http://localhost/angmysql/api.php').success(function(response) {
    $scope.users = response.data;
}); 

来自AngularDocs

The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.