使用Javascript连接到WCF Web服务

时间:2012-08-06 02:21:30

标签: javascript jquery asp.net wcf web-services

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

并调用公开的方法。

答案 1 :(得分:1)

如果您的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调用,并将内容写回流以使用数据调用回调函数。这在绑定元素上可用,如下所示:

<webHttpBinding>
        <binding name="defaultRestJsonp" crossDomainScriptAccessEnabled="true">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
          <security mode="None" />
        </binding>
</webHttpBinding>