zoukankan      html  css  js  c++  java
  • AngularJs轻松入门(九)与服务器交互

    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"}

    返回的数据会放在data参数中,我们可以获取服务器响应的内容將数据在视图中展示出来。

    这里写图片描述

    源码地址:https://github.com/rongbo-j/angularjs

  • 相关阅读:
    mysql 基础sql语句
    mysql存储引擎概述
    docker命令总结
    python链接postgresql
    Log4.net示例
    postgresql 使用游标笔记
    npm常用命令
    Nginx命令
    Ubuntu命令总结
    NHibernate总结
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6468881.html
Copyright © 2011-2022 走看看