我正在对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