Angular.js如何从PHP读取后台数据
之前已经有很多方法可以通过angular进行本地数据的读取。以前的例子中,大多数情况都是将数据存放到模块的$scope变量中,或者直接利用ng-init定义初始化的数据。但是这些方法都只为了演示其他功能的效果。这次来学习一下如何将Angular和PHP相结合,从后台读取数据。
首先,利用PHP,我们定义了一组后台数据,代码如下(test.php):
<?php
header("Access-Control-Allow-Origin:*");
header("Content-Type:application/json;charset=UTF-8");
$conn=newmysqli("myServer","myUser","myPassword","Northwind");
$result=$conn->query("SELECTCompanyName,City,CountryFROMCustomers");
$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);
?>
这段代码含义比较简单,连接数据库后,从数据库中利用sql语句选择相应的数据($conn->query("SELECTCompanyName,City,CountryFROMCustomers"))。之后,利用循环结构,将取出的数据以键值对的形式保存在$outp变量中。
接下来,在js中操作如下:
<divng-app="myApp"ng-controller="customersCtrl">
<table>
<trng-repeat="xinnames">
<td>{{x.Name}}</td>
<td>{{x.Country}}</td>
</tr>
</table>
</div>
<script>
varapp=angular.module('myApp',[]);
app.controller('customersCtrl',function($scope,$http){
$http.get("test.php")
.success(function(response){$scope.names=response.records;});
});
</script>
这里仍然应用了$http服务进行数据的读取,传入数据文件对应的url路径,成功后返回数据,并绑定到$scope.names变量上。
以上就是本文的全部内容,希望对大家的学习有所帮助。