1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 使用angularjs的$http.post异步提交数据时 服务器接收不了的问题

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

时间:2024-02-12 00:19:27

相关推荐

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

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

提交数据格式如下:

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

请求头格式如下:

直接代码块:

1 app.controller('payCtrl',function($scope,$http){ 2 //保存邮箱地址 3 $scope.emailEditSave=function(e){ 4 e=e || window.event; 5 preventSubmit(e); 6 var yes=confirm('是否确认更改或者添加邮箱地址?'); 7 if(yes ==true){ 8 $http.post('http://localhost/html/angular_post.php',{email:"liang@",cEmail:"liang@"}) 9 .success(function(resp){10 console.log(resp);11 });12 }13 14 };15 })

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

请求头如下:

直接代码块:

1 var app=angular.module('payApp',[],function($httpProvider) { 2 // Use x-www-form-urlencoded Content-Type 3 $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; 4 5 /** 6 * The workhorse; converts an object to x-www-form-urlencoded serialization. 7 * @param {Object} obj 8 * @return {String} 9 */10 var param = function(obj) {11 var query = '', name, value, fullSubName, subName, subValue, innerObj, i;12 13 for(name in obj) {14 value = obj[name];15 16 if(value instanceof Array) {17for(i=0; i<value.length; ++i) {18 subValue = value[i];19 fullSubName = name + '[' + i + ']';20 innerObj = {};21 innerObj[fullSubName] = subValue;22 query += param(innerObj) + '&';23}24 }25 else if(value instanceof Object) {26for(subName in value) {27 subValue = value[subName];28 fullSubName = name + '[' + subName + ']';29 innerObj = {};30 innerObj[fullSubName] = subValue;31 query += param(innerObj) + '&';32}33 }34 else if(value !== undefined && value !== null)35query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';36 }37 38 return query.length ? query.substr(0, query.length - 1) : query;39 };40 41 // Override $http service's default transformRequest42 $httpProvider.defaults.transformRequest = [function(data) {43 return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;44 }];45 46 });47 48 app.controller('payCtrl',function($scope,$http){49 //保存邮箱地址50 $scope.emailEditSave=function(e){51 e=e || window.event;52 preventSubmit(e);53 var yes=confirm('是否确认更改或者添加邮箱地址?');54 if(yes ==true){55 $http.post('http://localhost/html/angular_post.php',{email:"liang@",cEmail:"liang@"})56 .success(function(resp){57 console.log(resp);58 });59 }60 61 };62 })63 64 //阻止默认提交65 function preventSubmit(e){66 if(document.all){67 e.returnValue;68 }else{69 e.preventDefault();70 }71 }

主要是在angular.module()添加一个出来更改Content-type和序列化正常表单提交数据格式的函数,接着$http.post提交后的数据服务器就可正常获取。

转载:/liangsongbai/p/5221195.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。