Home  >  Article  >  Web Front-end  >  How to implement ajax request in AngularJS

How to implement ajax request in AngularJS

高洛峰
高洛峰Original
2016-12-06 09:34:141462browse

The example in this article describes how AngularJS implements ajax requests. Share it with everyone for your reference, as follows:

【HTML code】

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,user-scalable=no, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="" />
  <title>angularjs实现 ajax</title>
</head>
<body ng-app="HelloAjax">
  <div ng-controller="HelloAjax">
    <form>
      <input type="text" ng-model="username" />
      <input type="text" ng-model="email" />
    </form>
    <table>
     <tr ng-repeat="user in users">
       <td>{{user.username}}</td>
       <td>{{user.email}}</td>
     </tr>
    </table>
    <button ng-click="get_more();">get more</button>
  </div>
</body>
<script type="text/javascript" src="./js/angular.min.js" charset="utf-8"></script>
  <script type="text/javascript" src="ajax.js" charset="utf-8"></script>
</html>

【js code ajax.js】

var myModule = angular.module("HelloAjax",[]);
myModule.controller("HelloAjax",["$scope","$http",function HelloAjax($scope,$http){
  /*
  $scope.users=[{&#39;username&#39;:"zhangsan","email":"zs@11.com"},
    {&#39;username&#39;:"zhangsan2","email":"zs@22.com"},
    {&#39;username&#39;:"zhangsan3","email":"zs@33.com"}];
  */
  $scope.get_more = function(){
    $http({
        method: "POST",
        url: "./ajax.php",
        data:{&#39;username&#39;:$scope.username,
           &#39;email&#39;:$scope.email
          }
      }).
      success(function(data, status) {
       //$scope.status = status;
        $scope.users = data;
      }).
      error(function(data, status) {
       //$scope.data = data || "Request failed";
       //$scope.status = status;
     });
   }
}]);

【PHP code ajax.php】

<?php
//获取参数
$data = file_get_contents("php://input");
$user = json_decode($data);
//查询数据库
$conn = mysql_connect("localhost","root","");
mysql_select_db("test");
$sql ="select username,email from users ";
$res = mysql_query($sql,$conn);
$users = array();
while($row = mysql_fetch_assoc($res)){
  $users[] = $row;
}
//当然这里简化了插入数据库
$users[] = array(&#39;username&#39;=>$user->username,
         &#39;email&#39;=>$user->email);
//返回数据库
echo json_encode($users);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn