AngularJs $ http.post()不发送数据 [英] AngularJs $http.post() does not send data

查看:152
本文介绍了AngularJs $ http.post()不发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拉我的头发 - 任何人都可以告诉我为什么下面的语句不后的数据发送到指定的网址是什么? URL被称为但是当我打印$ _ POST在服务器上 - 我得到一个空数组。如果我将它添加到数据之前在控制台打印的消息 - 它显示了正确的内容。

  $ http.post('请求的URL,{消息:消息});

我也与数据串(具有相同效果),试了一下

  $ http.post('请求的URL,消息=+消息);

这似乎是工作,当我在下面的格式使用它:

  $ HTTP({
    方法:POST,
    网址:'请求的URL,
    数据:消息=+消息,
    标题:{内容类型:应用程序/ x-WWW的形式urlen codeD'}
});

但有与$ http.post()做这件事的一个方法 - 我总是有包括以头为它工作?我认为,上述内容类型指定发送的数据格式,但我可以把它作为JavaScript对象?


解决方案

我不得不使用asp.net MVC和的发现这里解决方案


  

有作为新人当中许多混乱为 AngularJS 为什么
   $ HTTP 服务速记功能( $ http.post()等)不出现
  是可热插拔的的jQuery 当量( jQuery.post()等)


  
  

不同之处在于如何的jQuery AngularJS 序列化和传输数据。从根本上讲,问题在于你选择的服务器端语言是无法在本机...了解AngularJS的传输默认情况下,的jQuery 使用传输数据

 的Content-Type:X-WWW的形式urlen codeD

和熟悉的富=酒吧和放大器;巴兹=教育部系列化


  
  

AngularJS ,但是使用传输数据

 内容类型:应用程序/ JSON

{富:酒吧,巴兹:萌}


  
  

JSON序列化,不幸的是语言 - 某些Web服务器值得注意的是
   PHP
的 - 不反序列化本身


工程就像一个魅力。

code

  //您的应用程序的根模块...
angular.module(MyModule的,[],功能($ httpProvider){
  //使用的X WWW的形式urlen codeD的内容类型
  $ httpProvider.defaults.headers.post ['内容类型'] ='应用/的X WWW的形式urlen codeD;字符集= UTF-8';  / **
   *的主力;转换一个对象的X WWW的形式urlen codeD序列化。
   * @参数{}对象OBJ
   * @返回字符串{}
   * /
  VAR参数=功能(OBJ){
    VAR的查询='',名称,价值,fullSubName,子名称,子值,innerObj,我;    对于(OBJ中的名称){
      值= OBJ [名]      如果(价值的instanceof阵列){
        对于(i = 0; I< value.length ++我){
          子值=值[I]
          fullSubName =名称+'['+ I +']';
          innerObj = {};
          innerObj [fullSubName] =子值;
          查询+ =参数(innerObj)+'&放大器;';
        }
      }
      否则,如果(价值的instanceof对象){
        对(价值SUBNAME){
          子值=值[SUBNAME]
          fullSubName =名称+'['+ SUBNAME +']';
          innerObj = {};
          innerObj [fullSubName] =子值;
          查询+ =参数(innerObj)+'&放大器;';
        }
      }
      否则,如果(价值==未定义和放大器;!&安培;价值== NULL!)
        查询+ = EN codeURIComponent(名)+=+ EN codeURIComponent(值)+'&放大器;';
    }    返回query.length? query.substr(0,query.length - 1):查询;
  };  //覆盖$ http服务的默认transformRequest
  $ httpProvider.defaults.transformRequest = [功能(数据){
    返回angular.isObject(数据)及&放大器;字符串(数据)!=='[目标文件]?参数(数据)的数据;
  }];
});

I'm pulling my hair out - could anyone tell me why the following statement does not send the post data to the designated url? The url is called but on the server when I print $_POST - I get an empty array. If I print message in the console before adding it to the data - it shows the correct content.

$http.post('request-url',  { 'message' : message });

I've also tried it with the data as string (with the same outcome):

$http.post('request-url',  "message=" + message);

It seem to be working when I use it in the following format:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

but is there a way of doing it with the $http.post() - and do I always have to include the header in order for it to work? I believe that the above content type is specifying format of the sent data, but can I send it as javascript object?

解决方案

I had the same problem using asp.net MVC and found the solution here

There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.)

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... By default, jQuery transmits data using

Content-Type: x-www-form-urlencoded

and the familiar foo=bar&baz=moe serialization.

AngularJS, however, transmits data using

Content-Type: application/json 

and { "foo": "bar", "baz": "moe" }

JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.

Works like a charm.

CODE

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});

这篇关于AngularJs $ http.post()不发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆