使用JQuery和WCF连接JSONP

时间:2010-09-22 20:28:12

标签: jquery wcf cross-domain jsonp

我正在尝试使用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 个答案:

答案 0 :(得分:2)

尝试更改

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

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

来自文档:

  

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

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