用angularJS中的$http服务碰到了一个问题:运用$http.post方法向后台传递数据时,后台的php页面获取不到data参数传过来的值。

不论是这种姿势:

$http.post( "1.php", { id: 1 }).success(function (data) {
  console.log(data);
  });

还是这种姿势:

$http({
 method: 'POST',
 url: '1.php',
 data: { id: 1 }
 }).success(function (data) {
 console.log(data);
 });

后台php中的$_POST或$_REQUEST都无法获取到data中的值:

<"htmlcode">
<form action="1.php" method="post">
 <input type="text" name="tid">
 <input type="submit" value="submit">
</form>

输出结果为:{"tid":"2"},也就是说表单里的值是可以获取的,但是用ajax发送的数据获取不了!

那么表单数据和ajax发送的post数据之间有什么差异呢?于是我悄悄瞄一眼请求头...

1.表单的请求头部:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8,ja;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 5
Content-Type: application/x-www-form-urlencoded
Cookie: a0537_times=1
Host: 127.0.0.1
Origin: http://127.0.0.1
Pragma: no-cache
Referer: http://127.0.0.1/angularTest/1.html
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36

2.ajax发送的数据的请求头部:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8,ja;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 10
Content-Type: application/json;charset=UTF-8
Cookie: a0537_times=1
Host: 127.0.0.1
Origin: http://127.0.0.1
Pragma: no-cache
Referer: http://127.0.0.1/angularTest/1.html
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36

问题一下子就出来了!表单发送的文本类型是表单类型,而angular的ajax默认发送的则是json数据。

那么怎么把Content-type给改了呢?于是我就打开了angular的官网,照着改一下请求头:

$http({
 method: 'POST',
 url: '1.php',
 data: { id : 1 }
 headers: {
  'Content-Type': 'application/x-www-form-urlencoded'
 }
 }).success(function (data) {
 console.log(data);
 });

于是输出结果为:{"{\"test\":1}":""},还是有问题。对象并没有自动地序列化(jQuery用习惯了都快忘了居然还有这个问题!)

那么解决方案有:

1.不写成对象的形式,直接写字符串:

$http({
 method: 'POST',
 url: '1.php',
 data: 'test=1',
 headers: {
  'Content-Type': 'application/x-www-form-urlencoded'
 }
 }).success(function (data) {
 console.log(data);
 });

2.重写angular中transformRequest,自己写一个转换方法:

 $http({
 method: 'POST',
 url: '1.php',
 data: $scope.data,
 headers: {
  'Content-Type': 'application/x-www-form-urlencoded'
 },
 transformRequest: function ( data ) {
  var str = '';
  for( var i in data ) {
  str += i + '=' + data[i] + '&';
  }
  return str.substring(0,str.length-1);
 }
 }).success(function (data) {
 console.log(data);
 });

3.重写angular中的transformRequest,简单粗暴地把jquery拿过来:

 $http({
 method: 'POST',
 url: '1.php',
 data: $scope.data,
 headers: {
  'Content-Type': 'application/x-www-form-urlencoded'
 },
 transformRequest: function ( data ) {
  return $.param(data);
 }
 }).success(function (data) {
 console.log(data);
 });

4.修改默认的transformations(这个不太熟,先看一眼官网上怎么说的):

Default Transformations

The $httpProvider provider and $http service expose defaults.transformRequest and defaults.transformResponse properties. If a request does not provide its own transformations then these will be applied.

You can augment or replace the default transformations by modifying these properties by adding to or replacing the array.

Angular provides the following default transformations:

Request transformations ($httpProvider.defaults.transformRequest and $http.defaults.transformRequest):

If the data property of the request configuration object contains an object, serialize it into JSON format.
Response transformations ($httpProvider.defaults.transformResponse and $http.defaults.transformResponse):

If XSRF prefix is detected, strip it (see Security Considerations section below).
If JSON response is detected, deserialize it using a JSON parser.

然后照抄:

app.config(['$httpProvider', function ( $httpProvider ) {
  $httpProvider.defaults.transformRequest = function ( data ) {
  var str = '';
  for( var i in data ) {
   str += i + '=' + data[i] + '&';
  }
  return str.substring(0,str.length-1);
  }
 }]);
<code class="language-javascript">$http({ 
 method: 'POST', 
 url: '1.php', 
 data: $scope.data, 
 headers: { 
  'Content-Type': 'application/x-www-form-urlencoded' 
 } 
 }).success(function (data) { 
 console.log(data); 
 });</code> 

以上这篇快速解决angularJS中用post方法时后台拿不到值的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
angularJS,post

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。