angularjs中$http模块POST请求request payload转form data

angularjs发起$http.post请求:

代码如下:

 $http({
     method:'post',
     url:'post.php',
     data:{name:"aaa",id:1,age:20}
 }).success(function(req){
     console.log(req);
 })

运行结果(chrome→network):

QQ图片20131227110729.jpg

这样的话在PHP中用$_POST是取不到的。

解决方案:

1.配置$httpProvider:

 var myApp = angular.module('app',[]);
 myApp.config(function($httpProvider){

   $httpProvider.defaults.transformRequest = function(obj){
     var str = [];
     for(var p in obj){
       str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
     }
     return str.join("&");
   }

   $httpProvider.defaults.headers.post = {
        'Content-Type': 'application/x-www-form-urlencoded'
   }

});

2.在post中配置:

 $http({
    method:'post',
    url:'post.php',
    data:{name:"aaa",id:1,age:20},
    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);
 })

运行结果(chrome→network):

form data

至此成功换成form data;

3.PHP中放弃$_POST;

$rawpostdata = file_get_contents("php://input");
$post = json_decode($rawpostdata, true);
//传的数据都在$post中了;

<!--End of the article-->

©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页