This article briefly introduces Angular. how does js read background data from PHP? In this article, Angular and PHP are combined to read data from the background, if you are interested, you can refer to many methods that can be used 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 time
How 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:
{{ x.Name }} |
{{ x.Country }} |
《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.