angularjs中封裝了一個$http服務,用來請求遠程資源
參見:HTTP API
其中封裝過的$http.post和$http.get使用起來比較方便
后台是php,用$_POST['name']接收,一直接收不到代碼,甚是奇怪
查閱文章所知,原來angular的$http服務和jquery的不一樣
原文:
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.
大意:
jquery傳輸數據用的Content-Type是:x-www-form-urlencoded,類似url傳參,而angularJS的Content-Type是 application/json,是使用JSON序列化傳參,而PHP正好默認不會接收后者。
根據老外的提議,改服務端代碼當然也可以,但是還是$_POST用的習慣,所以就將angular的傳參方式改為jquery的方式,下面是代碼,放在主module里就可以了
// 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; }]; });
Done!
原文鏈接:Link
