2012-02-26 63 views
1

我寫了一個WCF服務,它接受一個字符串並返回一個字符串。當我從我的javascript調用它時,它會導致顯示錯誤警報。調用WCF服務時JQuery.Post拋出錯誤

我試過閱讀API並且不確定我在做什麼錯誤或者如何顯示實際的錯誤信息。

這裏是我的javascript:

var path = "http://localhost:15286/Service.svc/SubmitTest?url=" + encodeURIComponent(info.srcUrl); 
var jqxhr = $.post(path, function() { 

    alert("success"); 
}) 
.success(function() { alert("second success"); }) 
.error(function(oEvent) { alert("error"); }) 
.complete(function() { alert("complete"); }); 
}; 

我看過通過調試服務時,它被調用,所以我想我的問題是關於JavaScript的它沒有錯誤返回字符串「Hello World」側。

WCF服務:

[ServiceContract] 
public interface IService 
{ 
    [WebInvoke(UriTemplate = "/Submit?input={value}")] 
    [OperationContract] 
    string Submit(string value); 
} 

public class Service : IService 
{ 
    public string Submit(string input) 
    { 
     return "hello world"; 
} 
+0

什麼響應內容類型是服務設置? – nnnnnn 2012-02-26 09:48:33

+0

您是否管理? – gdoron 2012-02-27 16:14:04

+0

對不起@gdoron,我不明白你的問題:( – BeepBoop 2012-02-28 08:50:54

回答

0

使用dataType參數,如果服務返回的 「Hello World」,那麼數據類型爲 「文本」:

var jqxhr = $.post(path, function() { 

    alert("success"); 
}, "text") // <==== 
.success(function() { alert("second success"); }) 
.error(function(oEvent) { alert("error"); }) 
.complete(function() { alert("complete"); }); 
}; 

dataTypeThe類型與預期的數據服務器。默認值:智能猜測(xml,json,script,text,html)。

並多次猜測是不是太「智能」 ......

+0

謝謝,我試過這個但結果相同:( – BeepBoop 2012-02-26 10:30:50

0
,你可能會面臨的跨域問題

嘗試添加

Headers.Add("Access-Control-Allow-Origin", "*"); 

在服務說的響應長相像

var Response = new HttpResponseMessage<string>("hello world"); 
Response.Headers.Add("Access-Control-Allow-Origin", "*"); 
return Response ; 
+0

對不起,你是建議我把這個添加到服務還是javascript? – BeepBoop 2012-02-26 10:31:46

+0

我應該更清楚了,加個訪問控制頭到服務響應 – Rafay 2012-02-26 10:59:07

+0

對不起,我已經更新了我的問題,包括我的服務中的代碼,我從字面上只是從我的函數返回一個字符串,我不知道我應該返回你提到的響應(我很新的WCF服務,這是我的第一個) – BeepBoop 2012-02-26 11:16:47