zoukankan      html  css  js  c++  java
  • angularJS发起$http.post请求后台收不到数据解决方案

    AngularJS发起$http.post请求

    代码如下:

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

    这时候你会发现收不到返回的数据,结果为null,这是因为要转换成form data。
    解决方案:

    配置$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'  
       }  
    
    });  

    或者在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);  
    })  
  • 相关阅读:
    Linux文件查找
    Linux之正则表达式
    linux文本处理
    Linux压缩归档管理
    spring-security问题记录
    mybatis-plus&springboot
    Mysql8- Public Key Retrieval is not allowed
    MySQL 5.7安装(linux)
    git把本地代码上传(更新)到github上
    linux相关(find/grep/awk/sed/rpm)
  • 原文地址:https://www.cnblogs.com/gongshunkai/p/6752647.html
Copyright © 2011-2022 走看看