Home  >  Article  >  Web Front-end  >  How Angular.js reads background data from PHP_AngularJS

How Angular.js reads background data from PHP_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:08:191458browse

There have been many methods to read local data through angular. In the previous examples, in most cases, the data is stored in the $scope variable of the module, or the initialized data is directly defined using ng-init. But these methods are only for demonstrating the effects of other functions. This time let’s learnhow to combine Angular and PHP to read data from the background.
First, using PHP, we defined a set of background data, the code is as follows (test.php):

<&#63;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); 
&#63;> 

The meaning of this code is relatively simple. After connecting to the database, use the sql statement to select the corresponding data from the database ($conn->query("SELECT CompanyName, City,Country FROM Customers")). Afterwards, the loop structure is used to save the retrieved data in the $outp variable in the form of key-value pairs.
Next, operate as follows in 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> 

The $http service is still used here to read data, and the url path corresponding to the data file is passed in. After success, the data is returned and bound to the $scope.names variable.

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn