从Web服务接收未定义的信息

时间:2013-12-11 19:42:18

标签: javascript jquery web-services jsonp

以下是我的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。

提前致谢!

1 个答案:

答案 0 :(得分: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);
});