[英]AngularJS - $http.post send data as json
我正在使用angularjs處理自動完成指令但有一些問題。
我有一個具有自動完成輸入的表單。 當我在那里輸入內容時, 術語變量將作為JSON發送:
但是,當我使用相同的功能(來自不同的角度控制器,但相同的功能)在另一種形式時, 術語變量發送完美,自動完成工作正常:
這是我的角度函數:
$scope.getCustomers = function (searchString) {
return $http.post("/customer/data/autocomplete",
{term: searchString})
.then(function (response) {
return response;
});
};
你覺得怎么了?
使用JSON.stringify()來包裝你的json
var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
$http.post(url, parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
考慮在$ http.post中顯式設置標題(我把應用程序/ json,因為我不確定您的示例中的哪兩個版本是工作的,但您可以使用application / x-www-form-urlencoded if它是另一個):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
我認為最合適的方法是在使用你的“get”請求時使用相同的代碼角度使用$httpParamSerializer
必須將它注入你的控制器,所以你可以簡單地執行以下操作而不必使用Jquery, $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.