使用Javascript连接到WCF Web服务

有谁知道如何使用Javascript连接到WCF Web服务?

此时我需要的是实际连接到Web服务,并通知连接成功。

有谁知道我怎么做到这一点?

如果您的WCF服务位于同一个域中,则可以使用以下函数执行调用

 function TestingWCFRestWithJson() { $.ajax({ url: "http://localhost/Service/JSONService.svc/GetDate", dataType: "json", type: "GET", success: function (data, textStatus, jqXHR) { // perform a success processing }, error: function (jqXHR, textStatus, errorThrown) { // show error to the user about the failure to invoke the service }, complete: function (jqXHR, textStatus) {//any process that needs to be done once the service call is compelte } }); } 

如果您的WCF服务位于调用应用程序域以外的其他域中,则需要执行JSONP调用,如下所示:

 function TestingWCFRestWithJsonp() { $.ajax({ url: "http://domain.com/Service/JSONPService.svc/GetDate", dataType: "jsonp", type: "GET", timeout: 10000, jsonpCallback: "MyCallback", success: function (data, textStatus, jqXHR) { }, error: function (jqXHR, textStatus, errorThrown) { }, complete: function (jqXHR, textStatus) { } }); } function MyCallback(data) { alert(data); } 

当使用JQuery的$ .ajax执行JSONP调用时,不会触发完整/成功/错误方法,而是触发所示的回调方法,需要由WCF服务处理。 WCF框架提供了一个属性“crossDomainScriptAccessEnabled”,用于标识请求是否为JSONP调用,并将内容写回流以使用数据调用回调函数。 这在绑定元素上可用,如下所示:

       

鉴于您已正确编写/配置了您的/ WCF服务,您应该能够加载以下URL:

 http://somedomain.com/somewcfservice.svc/jsdebug 

并调用暴露的方法。