angularjs中的$http详解

  1. 语法:  
  2.   
  3. 要将区别先弄清$http服务,它是对原生XMLHttpRequest对象的简单封装,是只能接受一个参数的方法,  
  4. 这个方法会返回一个promise对象,具有sccess和error两个方法。当然,我们也可以在响应返回时用then  
  5. 方法来处理,会得到一个特殊的参数,代表了对象的成功或失败信息,或者可以使用success和error回调  
  6. 代替。  
  7.    
  8.   
  9. $http(  
  10.   
  11. ).then(function success(resp){  
  12. //响应成功时调用,resp是一个响应对象  
  13. },function error(resp){  
  14. // 响应失败时调用,resp带有错误信息  
  15. }  
  16. );  
  17. 可以使用then()函数来处理$http服务的回调  
  18. then()函数接收的resp(响应对象)包含5个属性:   
  19.   
  20. 1. data(字符串或对象):响应体,就是后台返回的数据  
  21. 2. status:相应http的状态码,如200  
  22. 3. headers(函数):头信息的getter函数,可以接受一个参数,用来获取对应名字的值  
  23. 4. config(对象):生成原始请求的完整设置对象  
  24. 5. statusText:相应的http状态文本,如"ok"  
  25.   
  26.  $http({  
  27.      url:url,           //请求的url路径  
  28.      method:method,    //GET/DELETE/HEAD/JSONP/POST/PUT  
  29.      params:params ,   //转为  ?param1=xx1¶m2=xx2的形式  
  30.      data: data        //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用  
  31. }  
  32. }).success(function(response, status, header, config, statusText){  
  33.  //成功处理  
  34. }).error(function(data,header,config,status){  
  35.  //错误处理  
  36. });  
  37.   
  38. then写法与success参数是等价的,then方法和success方法的主要区别就是,then方法会接受到完整的响应对象,而  
  39. success则会对响应对象进行析构。  
  40.   
  41.   
  42.   
  43. AngularJS中的简单请求  ---  $http   --- 一个类似jquery的$.ajax的对象,用于异步请求  
  44.   语法:  
  45.   
  46.   
  47.         $http服务的设置对象:  
  48.             当我们把$http当成函数来使用时即$http(),需要传入一个对象,这个对象可以包含以下键  
  49.             1、method 字符串  表示发送的请求类型 get post jsonp等等  
  50.             2、url 字符串 绝对或者相对的URL,请求的目标  
  51.             3、params 字符串或对象 会被转化成查询字符串加到URL后面,如果不是字符串会被JSON序列化  
  52.             4、data 字符串或者对象 这个对象包含了被当做消息体发送给服务器的数据,一般在POST请求中使用,并且从angular1.3开始可以在POST请求里发送二进制数据  
  53.               如var blob = new Blob({name:’张三’}); $http({method:’get’,url:’/‘,data:blob});  
  54.             5、headers 对象 在我们做POST跨域和后台配合的时候就用到了headers,其代表随请求发送的HTTP头字符串  
  55.             6、xsrfHeaderName 字符串 保存XSFR令牌的HTTP头的名称  
  56.             7、xsrfCookieName  字符串 保存XSFR令牌的cookie的名称  
  57.             8、transformRequest 函数或函数组 用来对HTTP请求头和体信息进行转换,并返回转化后的版本,通常用于在请求发送给服务器之前对其序列化  
  58.             9、transformResponse 函数或函数组 用来HTTP响应头和响应体信息进行转换,并返回转化后的版本,通常用来反序列化  
  59.             10、cache 布尔或缓存对象 如果设置为true angularjs会用默认的$http缓存对GET请求进行缓存  
  60.             11、timout 数值或者promise对象,如果为数值那么请求会在指定的毫秒后结束(会跳到失败的error方法里) ,如果为对象那么promise对象在被resolve时请求会被中止,方法执行完毕再执行请求  
  61.             12、responseType 字符串 该选项会在请求中设置XMLHttpResponseType属性有以下类型: “”字符串默认,”arraybuffer”(arraybuffer),”blob”(blob对象),“document”(HTTP文档),”json“(从JSON对象解析出来的json字符串),”text“(字符串),”moz-blob“(Firefox的接收进度事件),”moz-chunked-text“(文本流),”moz-chunked-arraybuffer”(arraybuffer流)  
  62.   
  63.         $http服务的快捷方法  
  64.             $http提供了一些快捷方法让我们使用,一共有六个(其实是六种请求模式)  
  65.             1、$http.get(url字符串,config可选的配置-对象类型) 返回HttpPromise对象  
  66.             2、$http.delete(url字符串,config可选的配置-对象类型) 返回HttpPromise对象  
  67.             3、$http.head(url字符串,config可选的配置-对象类型) 返回HttpPromise对象  
  68.             4、$http.jsonp(url字符串,config可选的配置-对象类型) 返回HttpPromise对象  
  69.             5、$http.post(url字符串,data对象或字符串,config可选的配置-对象类型) 返回HttpPromise对象  
  70.             6、$http.put(url字符串,data对象或字符串,config可选的配置-对象类型) 返回HttpPromise对象  
  71.   
  72.   
  73.   
  74.   
  75.   
  76.          $http({  
  77.                  url:url,           //请求的url路径  
  78.                  method:method,    //GET/DELETE/HEAD/JSONP/POST/PUT  
  79.                  params:params ,   //转为  ?param1=xx1¶m2=xx2的形式  
  80.                  data: data        //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用  
  81.                }  
  82.                }).success(function(response, status, header, config, statusText){  
  83.                  //成功处理  
  84.                }).error(function(data,header,config,status){  
  85.                  //错误处理  
  86.                });  
  87.   
  88.          特别注意:  
  89.                   1.请求参数说明:  
  90.                             url:url,           //请求的url路径  
  91.                             method:method,    //GET/DELETE/HEAD/JSONP/POST/PUT  
  92.                             params:params ,   //转为  ?param1=xx1¶m2=xx2的形式  
  93.                             data: data        //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用  
  94.   
  95.                   2.响应参数说明:  
  96.                             response     ---  响应体,即:要请求的数据  
  97.                             status       ---  HTTP状态码  
  98.                             header      ---  头信息  
  99.                             config       ---  用来生成原始请求的完整设置对象  
  100.                             statusText   ---  相应的HTTP状态文本  
  101.   
  102.                   3.缓存HTTP请求  
  103.                             默认情况下,$http服务不会对请求进行本地缓存。在发送单独请求时,可通过向$http请求传递一个布尔参数来启用缓存  
  104.                             eg:  
  105.                                   $http.get({'/api/users.json',{cache:true}})  
  106.                                   .success(function(data){   })  
  107.                                   .error(function(data){   })  
  108.                             解析:  
  109.                                  第一次发送请求时,$http服务会向 /api/users.json发送一个GET请求,  
  110.                                  第二次发送同一个GET请求时,$http服务会从缓存中取回请求的结果,而不会真的发送一个HTTP GET请求  
  111.                                  设置启动缓存后,AngularJS默认会使用 $cacheFactory,这个服务在AngularJS启动时自动创建  
  112.                                  如果想要对AngularJS使用的缓存进行更多的自定义控制,可以向请求传入一个自定义的缓存实例代替true。  
  113.   
  114.   
  115.   
  116.       1.GET方式   --- params参数会转为  ?param1=xx1¶m2=xx2的形式  
  117.           1.$http请求:  
  118.                    $http({  
  119.                      url:"/api/users.json",  
  120.                      method:'GET',  
  121.                      params:{  
  122.                      'username':'jay'  
  123.                      }  
  124.                    }  
  125.                    }).success(function (response, status, headers, config) {  
  126.                        /*response   -- 成功返回的数据 
  127.                          status     -- 状态码 
  128.                          headers    -- 头信息 
  129.                          config     -- 其他信息 
  130.                        */  
  131.                      }).error(function (response) {  
  132.   
  133.                      }  
  134.                      });  
  135.           2.快捷请求:  
  136.                    $http.get(url, [config])  
  137.                         .success(function(data){})  
  138.                         .error(function(data){});  
  139.   
  140.        2.POST方式  
  141.                    $http({method : 'POST',params : { id:123}, data:{name:'john',age:27}, url : "/mypath"})  
  142.                    .success(function(response, status, headers, config){  
  143.                          //do anything what you want;  
  144.                    })  
  145.                    .error(function(response, status, headers, config){  
  146.                         //do  anything what you want;  
  147.                    });  
  148.   
  149.           2.快捷方式:  
  150.                      $http.post(url,  $scope.formData).success(function (response, status, headers, config) {  
  151.                                 ......  
  152.                              }).error(function (response) {  
  153.                                 ......  
  154.                              });  
  155.   
  156.   
  157.        3.$http提交表单  --- 与Spring MVC交互, 使用这种方式  
  158.   
  159.                通用方式:  
  160.                $http({  
  161.                        method: "POST",  
  162.                        url: url,  
  163.                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},  
  164.                        data: $.param($scope.formData)  
  165.                    }).success(function(result){  
  166.   
  167.                    }).error(function(result){  
  168.                    });  
  169.   
  170.                快捷方式:  
  171.                $http.post(url, $scope.formData)  
  172.                     .success(function(result){  
  173.                      })  
  174.                     .error(function(result){  
  175.                      });  
  176.   
  177.                   eg:  
  178.                       var data = {  
  179.                               "server":$scope.server,  
  180.                               "time":$("#time").val(),  
  181.                               "day":day  
  182.                       }  
  183.   
  184.                       $http({  
  185.                           method: "post",  
  186.                           url: ctx+'/player/lossPlayer/list.htm',  
  187.                           headers: {'Content-Type': 'application/x-www-form-urlencoded'},  
  188.                           data: $.param(data)  
  189.                       }).success(function(result){  
  190.                           if(result.tip!=undefined){  
  191.                               //当前绑定的数据清空  
  192.                               $scope.players = [];  
  193.                               alert(result.tip);  
  194.                           }else{  
  195.                               console.log(result.json);  
  196.                               $scope.players = $.parseJSON($.parseJSON(result.json).players);  
  197.                           }  
  198.                       });  
  199.   
  200.       4.使用$http指定的方法发送HTTP请求:  
  201.           get(url, [config]);  
  202.           delete(url, [config]);  
  203.           post(url, data, [config]);  
  204.           put(url, data, [config]);  
  205.   
  206.       5.发送jsonp请求:  
  207.           为了发送JSONP请求,url中必须包含JSON_CALLBACK参数, jsonp(url,config) 其中config是可选的  
  208.           eg:  
  209.           var promise=$http.jsonp("/api/users.json?callback=JSON_CALLBACK");
原文地址:https://www.cnblogs.com/benmumu/p/9025113.html