• AngularJS入门教程之与服务器(Ajax)交互操作示例


    AngularJS从Web服务器请求资源都是通过Ajax来完成,所有的操作封装在$http服务中,$http服务是只能接收一个参数的函数,这个参数是一个对象,用来完成HTTP请求的一些配置,函数返回一个对象,具有success和error两个方法。

    用法如下:

    $http({method:'post',url:'loginAction.do'
    }).success(function(data,status,headers,config){
    //正常响应回调
    }).error(function(data,status,headers,config){
    //错误响应回调
    });

    状态码在200-299之间,会认为响应是成功的,success方法会被调用,第一个参数data为服务器端返回的数据,status为响应状态码。后面两个参数不常用,这里不做介绍。有兴趣的朋友请参考AngularJs API文档。

    除此之外$http服务提供了一些快捷方法,这些方法简化了复杂的配置,只需要提供URL即可。比如对于post请求我们可以写成下面这个样子:

    $http.post("loginAction.do")
    .success(function(data,status,headers,config){
    //正常响应回调
    }).error(function(data,status,headers,config){
    //错误响应回调
    });
    下面来看一个案例:
    <!DOCTYPE html>
    <html ng-app="serverMod">
    <head lang="en">
     <meta charset="UTF-8">
     <script type="text/javascript" src="angular-1.3.0.14/angular.js"></script>
     <title>tutorial09</title>
    </head>
    <body ng-controller="ServerController" ng-init="init()">
    <p>name:{{name}}</p>
    <p>age:{{age}}</p>
    <button ng-click="getInfo()">请求</button>
    </body>
    <script>
     var serverMod = angular.module("serverMod",[]);
     serverMod.controller("ServerController",function($scope,$log,$http){
      $scope.init = function()
      {
       $log.info("init functionn");
      }
      $scope.getInfo = function()
      {
       $http.get("json/person.json").success(function(data,status){
        alert(status);
        $scope.name = data.name;
        $scope.age = data.age;
       });
      }
     });
    </script>
    </html>
    点击”请求”按钮,我们通过$http服务以get方式向服务器请求数据,服务器响应数据格式通常为一段Json,这里我们用一个文本文件代替,person.json内容如下:
    {"name":"Rongbo_J","age":"23"}
     
     
  • 相关阅读:
    分布式事务处理总结
    职业生涯的第一个三年
    Linux 启动SVN服务
    TensorFlow入门:安装常用的依赖模块
    TensorFlow入门:mac 安装 TensorFlow
    shiro 配置导图
    spring集成JPA的三种方法配置
    tomcat server 报错之 More than the maximum allowed number of cookies
    Jquery系列:checkbox 获取值、选中、设置值、事件监听等操作
    [转]Tomcat优化之内存、并发、缓存
  • 原文地址:https://www.cnblogs.com/reaf/p/6664962.html
Copyright © 2020-2023  润新知