源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

angularJS之$http:与服务器交互示例

  • 时间:2020-04-25 00:53 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:angularJS之$http:与服务器交互示例
在angularJS中与远程HTTP服务器交互时会用一个非常关键的服务-$http。 [list=1] [*]$http是angular中的一个核心服务,利用浏览器的xmlhttprequest或者via JSONP对象与远程HTTP服务器进行交互。[/*] [*]$http的使用方式和jquery提供的$.ajax操作比较相同,均支持多种method的请求,get、post、put、delete等。[/*] [*]$http的各种方式的请求更趋近于rest风格。[/*] [*]在controller中可通过与$scope同样的方式获取$http对象,e.g. function controller($scope,$http){}[/*] [/list] 下面进行$http服务的使用说明,调用如下:   
[u]复制代码[/u] 代码如下:
$http(config).success(function(data,status,headers,config){}).error(function(data,status,headers,config){});
1.config为一个JSON对象,其中主要包含该请求的url、data、method等,如{url:"login.do",method:"post",data:{name:"12346",pwd:"123"}}。 [list=1] [*]method  {String} 请求方式e.g. "GET"."POST"[/*] [*]url {String} 请求的URL地址[/*] [*]params {key,value} 请求参数,将在URL上被拼接成?key=value[/*] [*]data {key,value} 数据,将被放入请求内发送至服务器[/*] [*]cache {boolean} 若为true,在http GET请求时采用默认的$http cache,否则使用$cacheFactory的实例[/*] [*]timeout {number} 设置超时时间[/*] [/list] 2、success为请求成功后的回调函数,error为请求失败后的回调函数,这里主要是对返回的四个参数进行说明。 [list=1] [*]data 响应体[/*] [*]status 相应的状态值[/*] [*]headers 获取getter的函数[/*] [*]config 请求中的config对象,同上第1点   [/*] [/list] 为了方便大家与HTTP服务器进行交互,angularJS提供了各个请求方式下方法。 $http.put/post(url,data,config) url、name必填,config可选 $http.get/delete/jsonp/head(url,confid) url必填,config可选 url、data、config与$http的参数一致, 下面有一个simple demo用于展示如何使用$http()及$http.post()。
<!DOCTYPE HTML>
<html lang="zh-cn" >
<head>
  <meta charset="UTF-8">
  <title>CSSClasses</title>
  <script src="angular.min.js" type="text/javascript"></script>
<script type="text/javascript">
  function ctrl($http,$scope){
    $scope.login = function(user){
      $http.post("login.do",user).success(function(data, status, headers, config){
        alert("success");
      }).error(function(data, status, headers, config){
        alert("error");
      })
    }
    $scope.login1 = function(user){
      $http({url:"login.do",data:user}).success(function(data, status, headers, config){
        alert("success");
      }).error(function(data, status, headers, config){
        alert("error");
      })
    }
  }
</script>
</head>
<body ng-app>
  <div ng-controller="ctrl">
    <form name="loginFm">
      Name:<input ng-model="user.name" />
      pwd: <input ng-model="user.pwd" />
      <input type="button" value="login" ng-click="login(user)" />
      <input type="button" value="login1" ng-click="login1(user)" />
    </form>
  </div>

</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部