Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

angularjs - AngularJs $ http.post()不发送数据(AngularJs $http.post() does not send data)

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.

(当我打印$ _POST时,在服务器上调用url - 我得到一个空数组。)

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?

(但有没有办法用$ http.post()来做 - 并且我总是必须包含标题才能使它工作?)

I believe that the above content type is specifying format of the sent data, but can I send it as javascript object?

(我相信上面的内容类型是指定发送数据的格式,但我可以将其作为javascript对象发送吗?)

  ask by Spencer Mark translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(我使用asp.net MVC遇到了同样的问题,并在此处找到了解决方案)

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.)

(AngularJS的新手之间存在很多混淆,为什么$http服务速记函数( $http.post()等)似乎不能与jQuery等价物交换( jQuery.post()等))

The difference is in how jQuery and AngularJS serialize and transmit the data.

(不同之处在于jQueryAngularJS如何序列化和传输数据。)

Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS's transmission natively ... By default, jQuery transmits data using

(从根本上说,问题在于您选择的服务器语言本身无法理解AngularJS的传输...默认情况下, jQuery使用)

 Content-Type: x-www-form-urlencoded 

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

(和熟悉的foo=bar&baz=moe序列化。)

AngularJS , however, transmits data using

(然而, AngularJS使用传输数据)

 Content-Type: application/json 

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

(和{ "foo": "bar", "baz": "moe" })

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

(JSON序列化,遗憾的是一些Web服务器语言 - 特别是PHP -本身没有反序列化。)

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;
  }];
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...