關於angularjs中$http POST請求引數的問題
阿新 • • 發佈:2019-01-25
本人angularjs小白,今天遇到這樣一個問題。在angularjs中發出這樣一個POST請求
$http({
method: "POST",
url: "",
params: id
}).success();
在除錯中發現,引數在url上出現了,就是以?id=123124的形式出現,跟GET請求變成一樣的了,然後查了一下發現引數的寫法用GET的時候就是params,用POST/PUT/PATCH/DELETE就是data,修改後
$http({
method: "POST",
url: "" ,
data: id
}).success();
發現傳送的引數出現在了request payload裡,後端會認為引數非法無法獲取(前一種是序列化的引數a=bbb&c=ddd,後者是引數為一個物件)
於是查詢了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();
然後確實就轉成form data了,但是引數如果是物件還是不行
於是再查資料發現,如果引數是物件,還需要加上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,也就是把引數轉成序列化的形式,所以以後如果使用的話,乾脆就寫成序列化的形式就好了,省的還要再轉一道。jquery中有$.param()方法可以實現,angularjs裡面不知道有沒有。
文章來源:csdn