2013-10-29 83 views
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); 

回答

2

您可以處理此一對夫婦不同的方式:

  1. 你可以通過$ httpProvider設置頁眉默認值:http://docs.angularjs.org/api/ng $ HTTP#description_setting-HTTP報頭
  2. 你也可以使用Angular中的攔截器攔截$ http的想法來修改所有請求的配置對象:http:// http#description_interceptors
  3. 您也可以像上面那樣設置配置設置。

最大的問題是你可能會誤解配置的工作原理。在這裏看到這個問題:Angular, content type is not being generated correctly when using resource

+0

謝謝,現在我明白AngularJS'$ http'方法是如何工作的。 – zulucoda

相關問題