为你使用jQuery,请在下面找到一个样本消耗跨域WCF REST服务:
我的服务看起来如下:
[ServiceContract]
public interface IJSONPService
{
[OperationContract]
[WebGet]
string GetDate();
[OperationContract]
[WebInvoke]
string PostData(string name);
}
现在对于上述服务我的配置条目看起来如图所示:
<services>
<service name="Service.JSONPService">
<endpoint address="" binding="webHttpBinding" behaviorConfiguration="json" bindingConfiguration="defaultRestJsonp" contract="Service.IJSONPService">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="json">
<enableWebScript />
</behavior>
</behaviors>
</endpointBehaviors>
<webHttpBinding>
<binding name="defaultRestJsonp" crossDomainScriptAccessEnabled="true">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</webHttpBinding>
需要注意其中需要决定请求的护理是绑定元素“defaultRestJsonp”的crossDomainScriptAccessEnabled
属性为JSONP并适当转换的响应被包裹在由这是作为查询字符串现在
从您的网页的URL回调方法做下面的JavaScript调用上面的WCF REST服务,如下所示:
function TestingWCFRestWithJsonp() {
$.ajax({
url: "http://domain.com/Service/JSONPService.svc/GetDate",
dataType: "jsonp",
type: "GET",
timeout: 10000,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {alert('error');
},
complete: function (jqXHR, textStatus) {alert('complete');
}
});
}
function MyCallback(data) {
alert(data);
}
检出$ .ajax方法调用中的jsonpCallback属性。
的原始请求发送到Web服务调用看起来如下:
GET http://localhost/Service/JSONPService.svc/GetDate?callback=MyCallback&_=1343391683779 HTTP/1.1
Host: localhost
Connection: keep-alive
而且从WCF REST服务的原始响应看起来如下:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/x-javascript
Date: Fri, 27 Jul 2012 12:21:23 GMT
Content-Length: 27
MyCallback("27\/07\/2012");
注意:当您执行JSONP请求您的$ .ajax方法错误/完成/成功不会被调用。
也请张贴一些示例代码,你有你的服务看起来像和jQuery的使用? – Rajesh 2012-07-27 13:25:48