2013-12-11 82 views
0

這裏未定義的信息是代碼爲我的WebService,接收來自網絡服務

[WebService(Namespace = "http://mydomain.com/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class VBRService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string callJson(string x) 
    { 
     return "Worked =" + x; 
    } 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public void callJson2(string x, string callback) 
    { 
     StringBuilder sb = new StringBuilder(); 
     sb.Append(callback + "("); 

     var json = new JavaScriptSerializer().Serialize("aString"); 

     sb.Append(json); 
     sb.Append(");"); 

     Context.Response.Clear(); 
     Context.Response.ContentType = "application/json"; 
     Context.Response.Write(sb.ToString()); 
     Context.Response.End(); 
    } 
} 

這裏是JavaScript代碼,

$.ajax({ 
     crossDomain: true, 
     contentType: "application/json; charset=utf-8", 
     url: "http://localhost:31310/VBRService.asmx/callJson2", 
     data: { x:"someDataPassed", callback:onDataReceived }, 
     dataType: "jsonp", 
     error: function (data){ 
      alert(data.d); 
     } 
    }); 

    function onDataReceived(data) { 
     alert(data.d); 
     //  ^Here is where the data comes back as undefined. 
    } 

JavaScript的觸發關閉,打onDataReceived功能。我不太確定這是否是您如何響應webService執行回調,因爲沒有任何服務器端代碼要調用。

但是,對象數據在回調時未定義。這是跨域,所以我試圖弄清楚如何使用jsonp。

在此先感謝!

+0

你(和我們)需要知道返回的JSON格式是有得到任何東西在它外面的任何希望。 'console.log(data)' –

+0

另外,我很確定你的錯誤回調正在發生,並且xhr沒有'd'屬性。 –

+0

甚至更​​多的,jsonp請求不能定義contentType,並且會忽略crossDomain true參數,並且通常甚至不會執行錯誤回調。 –

回答

0

這是發送jsonp請求的正確方法。你太過於複雜。

$.ajax({ 
    url: "http://localhost:31310/VBRService.asmx/callJson2?callback=?", 
    dataType: "jsonp", 
    data: {x: "somedata"}, 
    success: function(data){ 
     console.log(data); 
    } 
}); 

備選:

$.getJSON("http://localhost:31310/VBRService.asmx/callJson2?callback=?",{x: "somedata"},function(data){ 
    console.log(data); 
}); 
+0

那麼,我必須改變我的web服務中的任何內容來解決這個問題嗎?對不起,剛開始使用json今天。謝謝! – user3003510

+0

我不知道,我不熟悉你使用的任何服務器語言。它看起來像只是試圖發送一個字符串爲json,通常json表示一個數組或結構,而不僅僅是一個簡單的字符串。 –