您的位置:首页 > 理论基础 > 计算机网络

使用angularjs的$http.post异步提交数据时,服务器接收不了的问题

2016-02-26 17:54 976 查看
一,在正常情况下,使用表单的post方法提交数据,默认请求头的Content-Type:application/x-www-form-urlencoded类型,

提交数据格式如下:



二,使用angularjs的$http.post提交数据,使用的是Content-Type:application/json类型,

请求头格式如下:



直接代码块:

app.controller('payCtrl',function($scope,$http){
//保存邮箱地址
$scope.emailEditSave=function(e){
e=e || window.event;
preventSubmit(e);
var yes=confirm('是否确认更改或者添加邮箱地址?');
if(yes ==true){
$http.post('http://localhost/html/angular_post.php',{email:"liang@163.com",cEmail:"liang@163.com"})
.success(function(resp){
console.log(resp);
});
}

};
})


三,所以把angularjs默认的json类型定义为正常application/x-www-form-urlencoded类型,同时把提交的数据序列化

请求头如下:



直接代码块:

var app=angular.module('payApp',[],function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

for(name in obj) {
value = obj[name];

if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}

return query.length ? query.substr(0, query.length - 1) : query;
};

// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];

});

app.controller('payCtrl',function($scope,$http){
//保存邮箱地址
$scope.emailEditSave=function(e){
e=e || window.event;
preventSubmit(e);
var yes=confirm('是否确认更改或者添加邮箱地址?');
if(yes ==true){
$http.post('http://localhost/html/angular_post.php',{email:"liang@163.com",cEmail:"liang@163.com"})
.success(function(resp){
console.log(resp);
});
}

};
})

//阻止默认提交
function preventSubmit(e){
if(document.all){
e.returnValue;
}else{
e.preventDefault();
}
}


主要是在angular.module()添加一个出来更改Content-type和序列化正常表单提交数据格式的函数,接着$http.post提交后的数据服务器就可正常获取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: