2013-12-11 83 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表示一个数组或结构,而不仅仅是一个简单的字符串。 –