我正在對WCF Web服務發出GET
請求。我的WCF服務位於http://localhost/RestService/RestService.svc/web/GetMessage
並具有以下接口:jQuery GET失敗,沒有錯誤消息
[OperationContract]
[WebGet(UriTemplate = "GetMessage", ResponseFormat = WebMessageFormat.Json)]
String GetMessage();
端點被正確配置,因爲我可以讓我的瀏覽器內的裸電話:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WebServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebEndpointBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="TestRestService.RestService"
behaviorConfiguration="WebServiceBehavior">
<endpoint name="RestWeb"
address="web"
binding="webHttpBinding"
behaviorConfiguration="WebEndpointBehavior"
contract="TestRestService.IRestService" />
</service>
</services>
</system.serviceModel>
通過導航在瀏覽器中調用它回覆:
{"GetMessageResult":"Hello World!"}
到目前爲止好。這裏沒有問題。就讓我們來看看在jQuery documentation用於執行GET
產量:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'http://localhost/RestService/RestService.svc/web/GetMessage',
type: 'GET',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (xhr, status, message) {
alert("Error: " + status + " " + message); }
});
</script>
</head>
<body>
</body>
</html>
我在使用jQuery 1.72小HTML測試頁運行此,我得到以下錯誤:
Error: error
是怎麼回事?錯誤消息處理程序that I found here給我絕對零有用的信息。簡單地說:
- 爲什麼我的GET失敗?
- 爲什麼錯誤信息是無用的?
事實證明,jQuery的本身不支持跨域Ajax請求作爲凱文乙suggested in his answer。爲了解決這個問題,我不得不切換到使用dataType: 'jsonp'
並添加webHttpBinding
啓用了crossDomainScriptEnabled
屬性:
<bindings>
<webHttpBinding>
<binding name="WebBindingWithScripts"
crossDomainScriptAccessEnabled="true">
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<endpoint name="RestWeb"
address="web"
binding="webHttpBinding"
behaviorConfiguration="WebEndpointBEhavior"
bindingConfiguration="WebBindingWithScripts"
contract="TestService.IRestService">
</endpoint>
當僅使用dataType: 'jsonp'
,除非您配置WCF服務,允許跨域腳本,你仍然會得到錯誤。
使用try瀏覽器的devtool(用於chrome ctrl + shift + J)。你能看到要求嗎?控制檯上的任何錯誤? – SuperSaiyan
嘗試刪除'dataType'並讓jquery推斷它。你也可以嘗試設置'dataType:'jsonp'。 –
你確定這個web服務正在返回一個MIME類型的json/application嗎? – Ian