Home >Web Front-end >HTML Tutorial >angular的post传参后台php无法接收_html/css_WEB-ITnose

angular的post传参后台php无法接收_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:21:351270browse

很多时候我们需要用ajax提交post数据,angularjs与jq类似,也有封装好的post。

但是jQuery的post明显比angularjs的要简单一些,人性化一些。

两者看起来没什么区别,用angularjs的$http提交的数据,在php服务器端却无法通过$_REQUEST/$_POST获取到。

这是因为两者的post对header的处理有所不同……jQuery会把作为JSON对象的myData序列化,而Angular不会。

解决方案:

修改Angular的$httpProvider的默认处理(最完美的解决方案)

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

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn