簡體   English   中英

在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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM