2012-08-06 187 views
0

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

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

有谁知道我该怎么做?

+0

'异步JavaScript和XML' – undefined 2012-08-06 02:23:10

回答

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的$就完整/成功/错误的方法不会被触发,而如被触发,其需要处理的回调方法进行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> 
1

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

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

,并呼吁公开的方法。

+0

您可以使用AJAX“POST”的WCF服务 – 2012-08-06 02:29:52

+0

或任何其他的方法可以接受; 'GET','PUT','DELETE'等... – xandercoded 2012-08-06 02:31:48