###先比較下他們的差別
$http的post . 請求默認的content-Type=application/json . 提交的是json對象的字符串化數據, . 后端無法從post中獲取, . 跨域請求是復雜請求,會發送OPTIONS的驗證請求,成功后才真正發起post請求
jQuery.post . 使用的是content-Type=application/x-www-form-urlencoded - . 提交的是form data, . 后端可以從post中獲取, . 簡單跨域請求,直接發送
###解決辦法有兩個:
1. 是后端支持復雜的跨域請求 那么后端就需要設置如下的信息
def options(self):
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Max-Age', 86400)
self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
self.write('')
后端post中拿不到數據,我們需要自己處理request的body,看看python和php的處理方式: python
#這種寫法支持多種content-Type提交
def POST(self):
if self.request.headers['Content-Type'].find('application/json') >= 0:
body = self.request.body
if body:
return json.loads(body.decode())
else:
return {}
else:
paras = {}
for k, v in self.request.body_arguments.items():
paras[k] = v[-1].decode()
return paras
php
<?
$params = json_decode(file_get_contents('php://input'));
?>
2. 配置AngularJS 配置$http服務的默認content-Type=application/x-www-form-urlencoded,如果是指配置這個的話,雖然提交的content-Type改了,但是提交的數據依然是個json字符串,不是我們想要的form data形式的鍵值對,需要實現param方法. Talk is cheap, i show you the code.
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;
};
//一個function數組,負責將請求的body,也就是post data,轉換成想要的形式
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
配合一點$resource的API參考,這個代碼就好懂了: https://docs.angularjs.org/api/ngResource/service/$resource
Note: 上述param方法定義的地方不要使用jQuery.param方法,因為jQuery.param方法會將要處理的對象上的function全執行一邊,把返回的值當做參數的值,這是我們不期望的,我們寫的這個param方法也是為了解決上面說的content-Type=x-www-form-urlencoded,但是提交的數據依然是json串的問題。
如果不使用$resource,還有一種方法
$scope.formData = {};
$http({
method: 'POST',
url: '/user/',
data: $.param($scope.formData), // pass in data as strings
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
參考 http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/