[英]$http.post request not working in angularJS?
這個問題已經在這個網站上被嚴重回答,但是他們都沒有幫助。 所以我再次問:
當我發出這樣的POST請求時:
var sectionTypeVM = new Object();
sectionTypeVM.SectionTypeId = 0;
sectionTypeVM.Name = $scope.message;
$http({
method: 'POST',
url: 'http://mtapi.azurewebsites.net/api/sectiontype',
dataType: 'json',
data: sectionTypeVM,
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
}).success(function (data) {
alert(data);
}).error(function (data) {
alert(data);
});
它工作正常,但是當我嘗試執行以下操作時:
$http({
method: 'POST',
url: 'http://mtapi.azurewebsites.net/api/sectiontype',
dataType: 'json',
data: $scope.message,
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
}).success(function (data) {
alert(data);
}).error(function (data) {
alert(data);
});
沒有。 為什么我需要用javascript方法創建一個單獨的對象並發送它,為什么我的angularJS對象不能直接發布(它們看起來一樣)? 是服務器端錯誤還是什么? 有一個解釋會有所幫助。
您的2個帖子之間的主要區別是,第一個發送了一個帶有兩個字段(名稱和SectionTypeId)的對象,而第二個僅發送了$ scope.message的內容。 我可能是錯的,但看起來$ scope.message是一個字符串。 但是,您正在將內容類型設置為application / json。
兩者之間的區別是第一個帖子發送了這個對象 :
{
SectionTypeId: 0,
Name: [
{"name"="abc", "id"="1"},
{"name"="bcd", "id"="2"}
]
}
當第二個帖子發送這個數組時 :
[
{"name"="abc", "id"="1"},
{"name"="bcd", "id"="2"}
]
您需要重組代碼,以便$ scope.message是服務器可以接受的有效json對象,或者將$ scope.message包裝在與第一個示例類似的對象中。
首先是發送sectionTypeVM
這是一個JavaScript對象,二是發送$scope.message
這,我假設是從指定字符串sectionTypeVM.Name
。 兩者並不相同。
盡管在此簡單示例中, var sectionTypeVM = new Object()
與var sectionTypeVM = {}
相同,但后者更清楚地說明了sectionTypeVM是對象文字的意圖。 由於您要將JSON發送到服務器,因此應首選對象文字表示法。
我假設$ scope.message只是一個字符串(或數組)。 第二個示例不起作用的原因可能是因為$ scope.message不是對象文字,並且您已將json
指定為期望的數據格式。 對象文字必須遵循以下格式:
var sectionTypeVM = {
property: 'foo',
property: 'bar'
};
如果您想修改第二個示例以使其起作用,則可以將數據有效載荷更改為對象文字符號:
$http({
method: 'POST',
url: 'http://mtapi.azurewebsites.net/api/sectiontype',
dataType: 'json',
data: { Name: $scope.message },
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
})
如果您的服務器滿足了第一次請求,則可以這樣發布
$http({
method: 'POST',
url: 'http://mtapi.azurewebsites.net/api/sectiontype',
dataType: 'json',
data: {SectionTypeId:0, Name: $scope.message},
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
}).success(function (data) {
alert(data);
}).error(function (data) {
alert(data);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.