4
我剛剛遇到了一個關於通過asp.net webservice檢索數據的奇怪問題。
使用JQuery的ajax方法時,頭部設置正確,數據在JSON中成功檢索。
JSON例如:
$.ajax({
type: "GET",
url: "service/TestService.asmx/GetTestData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callback,
error: function (err, xhr, res) {
alert(err);
}
});
請求頭用於上述如下:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/json; charset=utf-8
Host localhost
Referer http://localhost/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
X-Requested-With XMLHttpRequest
的效應初探標頭以上如下:
Cache-Control private, max-age=0
Content-Length 327
Content-Type application/json; charset=utf-8
Date Tue, 29 Oct 2013 17:59:56 GMT
Server Microsoft-IIS/7.5
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
能正常工作。
但是對於AngularJS $ http方法,請求標題內容類型值未設置,因此響應標題內容類型默認爲text/xml; charset=utf-8
。看看下面的例子:
$http({
method : 'GET',
url: 'service/TestService.asmx/GetTestData',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
}).success(callback);
請求頭以上情況如下,你會看到,Content-Type的丟失:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Host localhost
Referer http://localhost/ComponentsAndRepos/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
因此,對於上述的響應頭是以下:
Cache-Control private, max-age=0
Content-Encoding gzip
Content-Length 341
Content-Type text/xml; charset=utf-8
Date Tue, 29 Oct 2013 17:59:56 GMT
Server Microsoft-IIS/7.5
Vary Accept-Encoding
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
因此這迫使響應返回爲XML不是JSON,有沒有辦法解決此問題的方法?
謝謝你,
更新 由於Erstad斯蒂芬
這是通過添加data:{}
屬性$http
方法解決。
$http({
method : 'GET',
url: 'service/TestService.asmx/GetTestData',
data: {},
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
}).success(callback);
謝謝,現在我明白AngularJS'$ http'方法是如何工作的。 – zulucoda