Home >Backend Development >PHP Tutorial >Using Angularjs to read background data from PHP

Using Angularjs to read background data from PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 08:57:101134browse

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 learn how 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):

<?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);
?>
The meaning of this code is relatively simple. After connecting to the database, use sql statements 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, the operation in js is as follows:

<div ng-app="myApp" ng-c 
<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>
Here we still apply the $http service to read the data, pass in the url path corresponding to the data file, return the data after success, and bind it to the $scope.names variable .

The above introduces the use of Angularjs to read background data from PHP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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