zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    损失函数VS评估指标
    协程到底是什么?看完这个故事明明白白!
    一个故事看懂AI神经网络工作原理
    一个爬虫的故事:这是人干的事儿?
    深夜,我偷听到程序员要对session下手……
    突然挂了!Redis缓存都在内存中,这下完了!
    还不懂Redis?看完这个故事就明白了!
    可怕!公司部署了一个东西,悄悄盯着你!
    小白怎么入门网络安全?看这篇就够啦!
    CPU有个禁区,内核权限也无法进入!
  • 原文地址:https://www.cnblogs.com/lili-lili-lili-lili/p/6206509.html
Copyright © 2011-2022 走看看