代码之家  ›  专栏  ›  技术社区  ›  Chris Stewart

使用jquery和wcf连接jsonp

  •  0
  • Chris Stewart  · 技术社区  · 14 年前

    我正在尝试在jquery中使用jsonp进行跨域调用。在IE中,警报方法从未执行。在FF/Safari/Chrome中,它始终为空。我看了一下fiddler,wcf方法的结果如我所料,它是:

    method({"Name":"blah1","Data":"blah2"});
    

    这是我的javascript:

    $.getJSON("http://localhost:5603/MyService/?method=test", null, function (result) {
        alert("in test: " + result);
        $("#spText").html(result);
    });
    

    以下是wcf方法:

    [OperationContract]
    [WebInvoke(UriTemplate = "", Method = "GET", 
        BodyStyle=WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json)]
    public Message Blah()
    {
        var j = new { Name = "blah1", Data = "blah2" };
    
        JavaScriptSerializer s = new JavaScriptSerializer();
        string jsonClient = s.Serialize(j);
    
        return WebOperationContext.Current.CreateTextResponse("method(" + jsonClient + ");",
            "application/json; charset=utf-8", Encoding.UTF8);
    }
    

    我觉得我对这件事很感兴趣。有人能发现我做错了什么吗?

    1 回复  |  直到 13 年前
        1
  •  2
  •   Ken Redler    13 年前

    尝试改变

    http://localhost:5603/MyService/?method=test
    

    http://localhost:5603/MyService/?method=test&callback=?
    

    从文档中:

    如果URL包含字符串 "callback=?" 在URL中,请求被视为JSONP

    参考文献: http://api.jquery.com/jQuery.getJSON/

    推荐文章