快速解决angularJS中用post方法时后台拿不到值的问题


Posted in Javascript onAugust 14, 2018

用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中的值:

<?php
 echo json_encode($_POST);
?>

输出为一个空数组。为了测试php本身是不是真的获取不到值,我就写了个表单测试下:

<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方法时后台拿不到值的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
jQuery 性能优化指南(2)
May 21 Javascript
js封装的textarea操作方法集合(兼容很好)
Nov 16 Javascript
javascript轻量级模板引擎juicer使用指南
Jun 22 Javascript
jQuery将多条数据插入模态框的示例代码
Sep 25 Javascript
jQuery mobile 移动web(4)
Dec 20 Javascript
Javascript 字符串模板的简单实现
Feb 13 Javascript
Bootstrap每天必学之折叠(Collapse)插件
Apr 25 Javascript
利用纯Vue.js构建Bootstrap组件
Nov 03 Javascript
jQuery设置图片等比例缩小的方法
Apr 29 jQuery
TypeScript类型声明书写详解
Aug 28 Javascript
小程序简单两栏瀑布流效果的实现
Dec 18 Javascript
vue 实现setInterval 创建和销毁实例
Jul 21 Javascript
详解angular应用容器化部署
Aug 14 #Javascript
使用node.js实现微信小程序实时聊天功能
Aug 13 #Javascript
JQuery通过后台获取数据遍历到前台的方法
Aug 13 #jQuery
AngularJS实现与后台服务器进行交互的示例讲解
Aug 13 #Javascript
JS实现把一个页面层数据传递到另一个页面的两种方式
Aug 13 #Javascript
Angularjs 根据一个select的值去设置另一个select的值方法
Aug 13 #Javascript
AngularJS中ng-options实现下拉列表的数据绑定方法
Aug 13 #Javascript
You might like
造就帕卡马拉的帕卡斯是怎么被发现的
2021/03/03 咖啡文化
mysql 查询指定日期时间内sql语句实现原理与代码
2012/12/16 PHP
thinkphp实现多语言功能(语言包)
2014/03/04 PHP
php的ddos攻击解决方法
2015/01/08 PHP
网站被黑的假象--ARP欺骗之页面中加入一段js
2007/05/16 Javascript
传智播客学习之java 反射
2009/11/22 Javascript
jquery 应用代码 方便的排序功能
2010/02/06 Javascript
js中将具有数字属性名的对象转换为数组
2011/03/06 Javascript
js+数组实现网页上显示时间/星期几的实用方法
2013/01/18 Javascript
通过JQuery实现win8一样酷炫的动态磁贴效果(示例代码)
2013/07/13 Javascript
浅谈javascript中基本包装类型
2015/06/03 Javascript
jquery小火箭返回顶部代码分享
2015/08/19 Javascript
使用pcs api往免费的百度网盘上传下载文件的方法
2016/03/17 Javascript
JS实现鼠标框选效果完整实例
2016/06/20 Javascript
AngularJS入门教程之表格实例详解
2016/07/27 Javascript
jquery插件treegrid树状表格的使用方法详解(.Net平台)
2017/01/03 Javascript
详解React Native顶|底部导航使用小技巧
2017/09/14 Javascript
cdn模式下vue的基本用法详解
2018/10/07 Javascript
微信小程序点击保存图片到本机功能
2019/12/13 Javascript
[09:33]2015国际邀请赛第四日TOP10
2015/08/08 DOTA
Python中Collection的使用小技巧
2014/08/18 Python
通过C++学习Python
2015/01/20 Python
python排序方法实例分析
2015/04/30 Python
python文件操作相关知识点总结整理
2016/02/22 Python
Python闭包之返回函数的函数用法示例
2018/01/27 Python
python rsync服务器之间文件夹同步脚本
2019/08/29 Python
python画环形图的方法
2020/03/25 Python
详解Python中的文件操作
2021/01/14 Python
英国复古服装和球衣购买网站:3Retro Football
2018/07/09 全球购物
美国羽绒床上用品第一品牌:Pacific Coast
2018/08/25 全球购物
课前一分钟演讲稿
2014/08/26 职场文书
教师个人发展总结
2015/02/11 职场文书
汉语拼音教学反思
2016/02/22 职场文书
机关单位2016年创先争优活动总结
2016/04/05 职场文书
导游词之张家口
2019/12/13 职场文书
windows系统搭建WEB服务器详细教程
2022/08/05 Servers