欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-09 12:54:36
用angularjs中的$http服务碰到了一个问题:运用$http.post方法向后台传递数据时,后台的php页面获取不到data参数传过来的值。 不论是这种姿势:...

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