2010-09-22 68 views
0

我试图在JQuery中使用JSONP获得跨域调用。在IE中,警报方法从未执行过。在FF/Safari/Chrome中,它始终为空。我看着提琴手和来自WCF方法的结果是,我很期待,那就是:使用JQuery和WCF连接JSONP

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); 
} 

我觉得我真的很接近这个。任何人都可以发现我做错了什么吗?

回答

2

尝试改变

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

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

从文档:

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

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

+0

就是这样。有趣的是如何工作。我打算根据规范补充说明,并且已经有效地将其硬编码到原来的位置(原始的“?method = test”),直到我可以跳舞从WCF服务器的URL中取出该密钥,然后重新应用它在发送回应之前。事实证明,没有动态做这件事一直是个问题。谢谢您的帮助。 – 2010-09-23 17:29:14