Angular.js如何從PHP讀取后臺(tái)數(shù)據(jù)

字號(hào):


    這篇文章主要為大家簡(jiǎn)單介紹了Angular.js如何從PHP讀取后臺(tái)數(shù)據(jù),本文將Angular和PHP相結(jié)合,從后臺(tái)讀取數(shù)據(jù),感興趣的小伙伴們可以參考一下
    之前已經(jīng)有很多方法可以通過angular進(jìn)行本地?cái)?shù)據(jù)的讀取。以前的例子中,大多數(shù)情況都是將數(shù)據(jù)存放到模塊的$scope變量中,或者直接利用ng-init定義初始化的數(shù)據(jù)。但是這些方法都只為了演示其他功能的效果。這次來學(xué)習(xí)一下如何將Angular和PHP相結(jié)合,從后臺(tái)讀取數(shù)據(jù)。
    首先,利用PHP,我們定義了一組后臺(tái)數(shù)據(jù),代碼如下(test.php):
    <?php 
    header("Access-Control-Allow-Origin: *"); 
    header("Content-Type: application/json; charset=UTF-8"); 
    $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); 
    $result = $conn->query("SELECT CompanyName, City, Country FROM Customers"); 
    $outp = ""; 
    while($rs = $result->fetch_array(MYSQLI_ASSOC)) { 
      if ($outp != "") {$outp .= ",";} 
      $outp .= '{"Name":"' . $rs["CompanyName"] . '",'; 
      $outp .= '"City":"'  . $rs["City"]    . '",'; 
      $outp .= '"Country":"'. $rs["Country"]   . '"}';  
    } 
    $outp ='{"records":['.$outp.']}'; 
    $conn->close(); 
    echo($outp); 
    ?> 
    這段代碼含義比較簡(jiǎn)單,連接數(shù)據(jù)庫后,從數(shù)據(jù)庫中利用sql語句選擇相應(yīng)的數(shù)據(jù)($conn->query("SELECT CompanyName, City,Country FROM Customers"))。之后,利用循環(huán)結(jié)構(gòu),將取出的數(shù)據(jù)以鍵值對(duì)的形式保存在$outp變量中。
    接下來,在js中操作如下:
    <div ng-app="myApp" ng-controller="customersCtrl">  
    <table> 
     <tr ng-repeat="x in names"> 
      <td>{{ x.Name }}</td> 
      <td>{{ x.Country }}</td> 
     </tr> 
    </table> 
    </div> 
    <script> 
    var app = angular.module('myApp', []); 
    app.controller('customersCtrl', function($scope, $http) { 
      $http.get("test.php") 
      .success(function (response) {$scope.names = response.records;}); 
    }); 
    </script> 
    這里仍然應(yīng)用了$http服務(wù)進(jìn)行數(shù)據(jù)的讀取,傳入數(shù)據(jù)文件對(duì)應(yīng)的url路徑,成功后返回?cái)?shù)據(jù),并綁定到$scope.names變量上。
    以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。