天天看点

HTTP传值方式和请求方式/angular的请求方式

一、Http传值方式有2种:get、post

二、标准Http协议支持六种请求方法,即:get 、head、put、delete、post、options(通常情况下我们只用到了get和post的请求方式)

三、Http使用get请求接口的时候,一般直接get到数据就可以;如果使用put、delete、post请求接口,一般要先请求options来来检查服务器的性能(或者可以说是先做一下判断,options先对复杂的数据做一次处理与校验)

angular的get请求方式

$http({
    url: url,
    method: "get"
}).success(function(res) {
    console.log(res);
});
           

脚注:

get 请求方式传递数组 你需要:在要传递的字段后面加[] ;

但是post请求传递数组就无需在字段后面加[];

angular的post请求方式

angular的post请求,要转换成form data,请看以下代码:

注:以下代码来源于http://blog.csdn.net/fengzijinliang/article/details/51897991

$http({  
   method:'post',  
   url:'post.php',  
   data:{name:"aaa",id:,age:},  
   headers:{'Content-Type': 'application/x-www-form-urlencoded'},  
   transformRequest: function(obj) {  
     var str = [];  
     for(var p in obj){  
       str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));  
     }  
     return str.join("&");  
   }  
}).success(function(req){  
       console.log(req);  
})
           

angular的put请求方式

我们要使用PUT 请求 POST 提交

注:以下代码来源于http://www.jianshu.com/p/4b1b11591cdf

//用户登录
  postLogin : function(params) {
      params['_method'] = 'PUT';
      console.log(params);
      var deferred = $q.defer();
      var url = config.basePath  + 'admins/1.html?act=login';
      $http({
          method: 'POST',
          url: url,
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          transformRequest: function (obj) {
              var str = [];
              for (var o in obj)
                  str.push(encodeURIComponent(o) + "=" + encodeURIComponent(obj[o]));
              return str.join("&");
          },
          data: params
      }).success(
          function (data, status, header, config) {
              deferred.resolve(data);
          });
      return deferred.promise;
  },
           

或者是

$http({
         url: url,
         method: "POST",
         data: {
             "_method":'PUT',
             "name":aili
         },
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
         },
         transformRequest: function (obj) {
             var str = [];
             for (var o in obj)
                 str.push(encodeURIComponent(o) + "=" + encodeURIComponent(obj[o]));
             return str.join("&");
         },
     }).success(function(res) {
          console.log(res);
     })
           

angular的delete请求方式

我们要用DELETE 请求 GET提交

$http({
        url: url(url里面拼接参数),
         method: "DELETE",
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
         },
         transformRequest: function (obj) {
             var str = [];
             for (var o in obj)
                 str.push(encodeURIComponent(o) + "=" + encodeURIComponent(obj[o]));
             return str.join("&");
         },
     }).success(function(res) {
         console.log(res);
     })
           

脚注

有问题可以联系QQ:523015682

继续阅读