当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular.js如何从PHP读取后台数据

Angular.js如何从PHP读取后台数据

2018年06月17日  | 移动技术网IT编程  | 我要评论

之前已经有很多方法可以通过angular进行本地数据的读取。以前的例子中,大多数情况都是将数据存放到模块的$scope变量中,或者直接利用ng-init定义初始化的数据。但是这些方法都只为了演示其他功能的效果。这次来学习一下如何将angular和php相结合,从后台读取数据
首先,利用php,我们定义了一组后台数据,代码如下(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); 
?> 

 这段代码含义比较简单,连接数据库后,从数据库中利用sql语句选择相应的数据($conn->query("select companyname, city,country from customers"))。之后,利用循环结构,将取出的数据以键值对的形式保存在$outp变量中。
接下来,在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> 

 这里仍然应用了$http服务进行数据的读取,传入数据文件对应的url路径,成功后返回数据,并绑定到$scope.names变量上。

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网