本人angularjs小白奔坟,今天遇到這樣一個問題榄笙。在angularjs中發(fā)出這樣一個POST請求
$http({
method: "POST",
url: "",
params: id
}).success();
在調(diào)試中發(fā)現(xiàn),參數(shù)在url上出現(xiàn)了砚著,就是以?id=123124的形式出現(xiàn)次伶,跟GET請求變成一樣的了,然后查了一下發(fā)現(xiàn)參數(shù)的寫法用GET的時候就是params稽穆,用POST/PUT/PATCH/DELETE就是data冠王,修改后
$http({
method: "POST",
url: "",
data: id
}).success();
發(fā)現(xiàn)發(fā)送的參數(shù)出現(xiàn)在了request payload里,后端會認為參數(shù)非法無法獲壬嘞狻(前一種是序列化的參數(shù)a=bbb&c=ddd柱彻,后者是參數(shù)為一個對象)
于是查詢了POST表單請求提交時,使用的Content-Type是application/x-www-form-urlencoded餐胀,而使用原生AJAX的POST請求如果不指定請求頭RequestHeader哟楷,默認使用的Content-Type是text/plain;charset=UTF-8,在html中form的Content-type默認值:Content-type:application/x-www-form-urlencoded骂澄。修改為
$http({
method: "POST",
url: "",
data: id,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success();
然后確實就轉(zhuǎn)成form data了吓蘑,但是參數(shù)如果是對象還是不行
于是再查資料發(fā)現(xiàn),如果參數(shù)是對象坟冲,還需要加上transformRequest
$http({
method: "POST",
url: "",
data: id,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function(obj) {
var str = [];
for (var p in obj) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
}).success();
這樣終于可以了磨镶,其實仔細看transformRequest,也就是把參數(shù)轉(zhuǎn)成序列化的形式健提,所以以后如果使用的話琳猫,干脆就寫成序列化的形式就好了,省的還要再轉(zhuǎn)一道私痹。jquery中有$.param()方法可以實現(xiàn)脐嫂,angularjs里面不知道有沒有。