发表于: 2017-04-24 23:43:26
1 1162
今天完成的事:
参加老大组织的组内会议
修补任务7留下的坑
完成任务8搜索页的静态页面
明天计划的事:
继续任务8
angular学习
遇到的问题:
1,angular js 在做$http 请求时:
- $http({
- method: "POST",
- url: "",
- data: id
- }).success();
发现发送的参数出现在了request payload里,后端会认为参数非法无法获取
- $http({
- method: "POST",
- url: "",
- data: id,
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
- }).success();
然后确实就转成form data了,但是参数如果是对象还是不行
于是再查资料发现,如果参数是对象,还需要加上transformRequest
- $http({
- method: "POST",
- url: "",
- data: id,
- 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();
这样终于可以了
其实仔细看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请求有了深入而细致的了解。
评论