2011-07-15 166 views
3

我有一個WCF服務,這是我最好調用一個方法:跨域調用WCF服務

[OperationContract] 
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)] 
    double?[] GetPoints(string tourname); 

我檢查通過WCF測試客戶端,它工作正常

所以我需要從html頁面調用這個方法。它應該從跨域的其他計算機上運行。

我寫somethig使用jQuery 1-6-2.min.js:

var varType; 
var varUrl; 
var varData; 
var varContentType; 
var varDataType; 
var varProcessData; 

function CallService() { 
     alert("CallService"); 
       $.ajax({ 
        type   : varType, //GET or POST or PUT or DELETE verb 
        url   : varUrl, // Location of the service 
        data   : varData, //Data sent to server 
        contentType : varContentType, // content type sent to server 
        dataType  : varDataType, //Expected data format from server 
        processdata : varProcessData, //True or False 
        success  : function(msg) {//On Successfull service call 
        ServiceSucceeded(msg);      
        }, 
        error: ServiceFailed// When Service call fails 
       }); 
     } 

function Start() { 
    varType = "POST"; 
    varUrl = "http://localhost:1592/TourService.svc/GetPoints"; 
    varData = '{"tourname ":"customname"}'; 
    varContentType = "application/json; charset=utf-8"; 
    varDataType = "json"; 
    varProcessData = true; 
    CallService(); 
} 

function ServiceSucceeded(result) { 
    alert("ServiceSucceeded"); 
    alert(result); 
} 

function ServiceFailed(result) { 
    alert('Service call failed: ' + result.status + ' ' + result.statusText); 
    varType = null; 
    varUrl = null; 
    varData = null; 
    varContentType = null; 
    varDataType = null; 
    varProcessData = null; 
} 

但是ServiceFailed函數調用時使用提示 「服務調用失敗0錯誤」

如何使一個跨WCF服務的調用域?(使用jQuery與否)

感謝

+1

爲什麼你認爲跨域調用的是什麼問題?並且請更好地分析錯誤發生的位置。消息「0錯誤」僅表明原始錯誤消息未正確轉發給jQuery錯誤回調。 – Codo

回答

1

爲WCF的.NET Framework 4的JSON回調內置現在,

我覺得jquery1.5開始,他們就增加了以下選項,跨域,試試下面的代碼

$.ajax({ 
    type: "POST", 
    dataType: "html", 
    crossDomain: true, 
    url: "http://www.domain.com/page.aspx", 
    error: function() { 
     alert("error"); 
    }, 
    success: function(msg){ 
     alert(msg); 
    } 
}); 
+0

不,不幸的是,這段代碼不起作用 –

+0

@illya,如果你沒有使用.net framework 4,請點擊這個鏈接,我們使用了這個並且實現了你正在尋找的東西http://jasonkelly.net/2009/05 /使用-jquery-jsonp-for-cross-domain-ajax-with-wcf-services/ – kobe

+0

這與我的答案中的鏈接相同BTW –