AngularJS实现ajax请求的方法

【HTML 代码】


1
<!DOCTYPE html> 2 <html> 3 <head> 4   <meta charset="utf-8"> 5   <meta name="viewport" content="width=device-width,user-scalable=no, initial-scale=1"> 6   <link rel="stylesheet" type="text/css" href="" /> 7   <title>angularjs实现 ajax</title> 8 </head> 9 <body ng-app="HelloAjax"> 10   <div ng-controller="HelloAjax"> 11     <form> 12       <input type="text" ng-model="username" /> 13       <input type="text" ng-model="email" /> 14     </form> 15     <table> 16      <tr ng-repeat="user in users"> 17        <td>{{user.username}}</td> 18        <td>{{user.email}}</td> 19      </tr> 20     </table> 21     <button ng-click="get_more();">get more</button> 22   </div> 23 </body> 24 <script type="text/javascript" src="./js/angular.min.js" charset="utf-8"></script> 25   <script type="text/javascript" src="ajax.js" charset="utf-8"></script> 26 </html>

【js代码 ajax.js】

 1 var myModule = angular.module("HelloAjax",[]);
 2 myModule.controller("HelloAjax",["$scope","$http",function HelloAjax($scope,$http){
 3   /*
 4   $scope.users=[{'username':"zhangsan","email":"zs@11.com"},
 5     {'username':"zhangsan2","email":"zs@22.com"},
 6     {'username':"zhangsan3","email":"zs@33.com"}];
 7   */
 8   $scope.get_more = function(){
 9     $http({
10         method: "POST",
11         url: "./ajax.php",
12         data:{'username':$scope.username,
13            'email':$scope.email
14           }
15       }).
16       success(function(data, status) {
17        //$scope.status = status;
18         $scope.users = data;
19       }).
20       error(function(data, status) {
21        //$scope.data = data || "Request failed";
22        //$scope.status = status;
23      });
24    }
25 }]);

【PHP代码 ajax.php】

 1 <?php
 2 //获取参数
 3 $data = file_get_contents("php://input");
 4 $user = json_decode($data);
 5 //查询数据库
 6 $conn = mysql_connect("localhost","root","");
 7 mysql_select_db("test");
 8 $sql ="select username,email from users ";
 9 $res = mysql_query($sql,$conn);
10 $users = array();
11 while($row = mysql_fetch_assoc($res)){
12   $users[] = $row;
13 }
14 //当然这里简化了插入数据库
15 $users[] = array('username'=>$user->username,
16          'email'=>$user->email);
17 //返回数据库
18 echo json_encode($users);

 原文地址:http://www.jb51.net/article/97924.htm

原文地址:https://www.cnblogs.com/lili-lili-lili-lili/p/6206509.html