2012-08-06 129 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