发表于: 2017-04-24 23:43:26

1 1164


今天完成的事:

参加老大组织的组内会议

修补任务7留下的坑

完成任务8搜索页的静态页面

明天计划的事:

继续任务8

angular学习

遇到的问题:

1,angular js 在做$http 请求时:

  1. $http({  
  2.             method: "POST",  
  3.             url: "",  
  4.             data: id  
  5.         }).success();  

发现发送的参数出现在了request payload里,后端会认为参数非法无法获取

于是查询了POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求如果不指定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8,在html中form的Content-type默认值:Content-type:application/x-www-form-urlencoded修改为

  1. $http({  
  2.             method: "POST",  
  3.             url: "",  
  4.             data: id,  
  5.             headers: { 'Content-Type''application/x-www-form-urlencoded' }  
  6.         }).success();  

然后确实就转成form data了,但是参数如果是对象还是不行


于是再查资料发现,如果参数是对象,还需要加上transformRequest

  1. $http({    
  2.             method: "POST",    
  3.             url: "",    
  4.             data: id,    
  5.             headers: { 'Content-Type''application/x-www-form-urlencoded' },    
  6.             transformRequest: function(obj) {    
  7.                 var str = [];    
  8.                 for (var p in obj) {    
  9.                     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));    
  10.                 }    
  11.                 return str.join("&");    
  12.             }  
  13.         }).success();    



这样终于可以了

其实仔细看transformRequest,也就是把参数转成序列化的形式,所以以后如果使用的话,干脆就写成序列化的形式就好了,省的还要再转一道。jQuery中有$.param()方法可以实现

最终完整代码

var myApp=angular.module('myApp',['ngMessages'])

    myApp.controller('MainCtrl',function($scope,$http){

    $scope.login=function(){

        $scope.fromData={name:$scope.username,pwd:$scope.password}

        $http({

            method:'post',

            url:'/carrots-admin-ajax/a/login',

            headers: {'Content-Type':'application/x-www-form-urlencoded'},

            data:$.param($scope.fromData),

        }).then(function(res){

          console.log(res.data)

        })

    };

 });

这里需要在html里引入JQ

收获:

1,在老大的会议了明确了自己的学习目标,并不能单纯的为了完成任务而去使用代码,终极目标是为了掌握其原理

2,对$http请求有了深入而细致的了解。


返回列表 返回列表
评论

    分享到