How does Angular. js read background data from PHP and angular. js reads background data?
There have been many ways to read local data through angular. In most cases, data is stored in the $ scope variable of the module, or initialized data is defined using ng-init directly. However, these methods are only used to demonstrate the effects of other functions. Learn this timeHow to combine Angular and PHP to read data from the background.
First, we define a set of background data using PHP. 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 in the database to SELECT the corresponding data ($ conn-> query ("SELECT CompanyName, City, Country FROM MERs ")). Then, the retrieved data is saved as a key-value pair in the $ outp variable using the cyclic structure.
Next, perform the following operations 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 applied to read data, pass in the url path corresponding to the data file, return the data, and bind it to the $ scope. names variable.
The above is all the content of this article, hoping to help you learn.
Articles you may be interested in:
- Use js to call php In the background for data processing original code
- Php json data parsing code
- Php json format data interaction instance code details
- How to obtain json data in post using php
- How php and js transmit data through json
- How to exchange data between PHP and JavaScript using Json
- Android accesses php to retrieve json data instances
- Use PHP to receive POST data and parse json data
- Php return json data function instance
- How to Use ajax to receive json data in ThinkPHP