使用Javascript连接到WCF Web服务

Use Javascript to connect to WCF Web Service

本文关键字:Web 服务 WCF Javascript 连接 使用      更新时间:2023-09-26

有人知道如何使用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调用时,不会触发complete/success/error方法,而是触发需要由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>

如果您正确地编写/配置了WCF服务,您应该能够加载以下url:

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

并调用公开的方法。