使用 JQuery 和 WCF 连接 JSONP

发布于 2024-09-24 16:54:49 字数 948 浏览 0 评论 0原文

我正在尝试在 JQuery 中使用 JSONP 进行跨域调用。在 IE 中,alert 方法从未执行。在 FF/Safari/Chrome 中,它始终为 null。我查看了 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);
}

我觉得我非常接近这一点。有人能发现我做错了什么吗?

I'm trying to get a cross domain call to work using JSONP within JQuery. In IE, the alert method never executed. In FF/Safari/Chrome, it's always null. I looked at Fiddler and the result from the WCF method is as I'm expecting, which is:

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

Here's my JavaScript:

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

Here's the WCF method:

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

I feel like I'm really close on this. Can anyone spot anything I'm doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山人契 2024-10-01 16:54:49

尝试更改

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

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

来自文档:

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

引用:http://api.jquery.com/jQuery.getJSON/

Try changing

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

to

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

From the documentation:

If the URL includes the string "callback=?" in the URL, the request is treated as JSONP

References: http://api.jquery.com/jQuery.getJSON/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文