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

 更新时间:2018年08月14日 08:38:53   作者:zsgod  
今天小编就为大家分享一篇快速解决angularJS中用post方法时后台拿不到值的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

相关文章

  • 如何通过简单的代码描述Angular父组件、子组件传值

    如何通过简单的代码描述Angular父组件、子组件传值

    Vue组件是学习Vue框架最比较难的部分,下面这篇文章主要给大家介绍了关于如何通过简单的代码描述Angular父组件、子组件传值的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-04-04
  • 详解在Angular4中使用ng2-baidu-map的方法

    详解在Angular4中使用ng2-baidu-map的方法

    这篇文章主要介绍了在Angular4中使用ng2-baidu-map的方法,本文分步骤给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-06-06
  • Angular开发者指南之入门介绍

    Angular开发者指南之入门介绍

    本篇文章主要介绍了Angular开发者指南的入门知识,具有很好的参考价值。下面跟着小编一起来看下吧
    2017-03-03
  • 详解Angular.js指令中scope类型的几种特殊情况

    详解Angular.js指令中scope类型的几种特殊情况

    AngularJs最重要也是最难理解的模块之一就是它的指令(directive)了,自定义指令配置有很多个参数,下面这篇文章主要介绍了关于Angular.js指令中scope类型的几种特殊情况,需要的朋友可以参考下。
    2017-02-02
  • 什么是 AngularJS?AngularJS简介

    什么是 AngularJS?AngularJS简介

    这篇文章主要介绍了什么是 AngularJS?AngularJS简介,本文讲解了AngularJS方方面面的基础知识,AngularJS 是一个为动态WEB应用设计的结构框架。它能让你使用HTML作为模板语言,通过扩展HTML的语法,让你能更清楚、简洁地构建你的应用组件,需要的朋友可以参考下
    2014-12-12
  • AngularJS基础知识

    AngularJS基础知识

    这篇文章主要介绍了AngularJS基础知识,包括AngularJS定义和特点以及构建AngularJS应用的方法,推荐给大家。
    2014-12-12
  • angularJS结合canvas画图例子

    angularJS结合canvas画图例子

    这篇文章主要介绍了angularJS结合canvas画图例子的方法,需要的朋友可以参考下
    2015-02-02
  • angular学习之从零搭建一个angular4.0项目

    angular学习之从零搭建一个angular4.0项目

    本篇文章主要介绍了从零搭建一个angular4.0项目,主要用到的工具angular4.0、angular-cli、npm(v3.10.8)、node(v6.2.0),有兴趣的可以了解一下
    2017-07-07
  • Angular.js实现扫码枪扫码并生成二维码

    Angular.js实现扫码枪扫码并生成二维码

    这篇文章主要为大家介绍了Angular.js实现扫码枪扫码并生成二维码示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • Angular依赖注入系统里Injection token PLATFORM_ID使用场景详解

    Angular依赖注入系统里Injection token PLATFORM_ID使用场景详解

    这篇文章主要为大家介绍了Angular依赖注入系统里Injection token PLATFORM_ID使用场景详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11

最新评论