angular入门-与服务器交互

与服务器端交互主要依赖的服务是$http,其实类似jquery 的get方法

$http的使用方式和jquery提供的$.ajax操作比较相同,均支持多种method的请求,get、post、put、delete等。

$http(config).success(function(data,status,headers,config){}).error(function(data,status,headers,config){});

代码 

//controller.js
routeApp.controller('RouteListCtl',function($scope,$http) {
     $http.get('http://xxxxxxx/angularjs/students.json')
         .success(function  (data,status,header,config) {
        $scope.items = data;
        });
});
routeApp.controller('RouteDetailCtl',function($scope, $routeParams,$http) {
    $scope.id = $routeParams.id;
    $scope.content = $routeParams.content;
    console.log($routeParams);
});
  1. config为一个JSON对象,其中主要包含该请求的url、data、method等,如{url:"login.do",method:"post",data:{name:"12346",pwd:"123"}}。
    • 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} 设置超时时间

  2、success为请求成功后的回调函数,error为请求失败后的回调函数,这里主要是对返回的四个参数进行说明。

    • data 响应体
    • status 相应的状态值
    • headers 获取getter的函数
    • config 请求中的config对象

  

  为了方便大家与HTTP服务器进行交互,angularJS提供了各个请求方式下方法。

      $http.put/post(url,data,config) url、name必填,config可选

      $http.get/delete/jsonp/head(url,confid) url必填,config可选

  url、data、config与$http的参数一致,

posted @ 2014-07-04 09:58  昊天翱翔  阅读(610)  评论(0编辑  收藏  举报