【问题标题】:Call external site webmethod using jsonp?使用 jsonp 调用外部站点 web 方法?
【发布时间】:2012-04-17 08:18:09
【问题描述】:

我正在尝试调用外部站点 web 方法,并发布一些数据。我尝试了很多不同的方法,仍然无法获得要调用的方法。

这是我的js代码:

$.ajax({
            url: "http://sitename.com/methods.aspx/mywebmethod",
            data: "{'id':'" + 4 + "'}",
            dataType: "jsonp",
            type: "GET",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });

这是我的网络方法代码:

[WebMethod()]
        public static bool mywebmethod(int id)
        {
if(id != 0){
            return true;}
else{return false;}
        }

我总是得到同样的回应

Error: jQuery{code} was not called

我错过了什么?

【问题讨论】:

    标签: c# asp.net json jsonp


    【解决方案1】:

    JSONP 并不神奇。

    您只能使用 JSONP 从返回 JSONP script 的 URL 中读取数据。
    ASP.Net WebMethods 不支持 JSONP。

    【讨论】:

    • 你不能。您需要了解 JSONP 的工作原理。 en.wikipedia.org/wiki/JSONP
    • 是的,使用服务器端脚本调用外部网络服务。忘记javascript。要了解为什么您应该忘记 javascript,请遵循 SLaks 的建议并阅读 JSONP 以了解它的工作原理,并阅读浏览器内置的同源策略限制,它会阻止您发送跨域 AJAX 请求。
    • 在我的情况下,我需要从客户端拨打电话
    • 在这种情况下,您必须修改远程服务,使其返回 JSONP 而不是 JSON。
    【解决方案2】:

    我猜你缺少正确的属性,如下(在 .asmx 定义中):

        [WebMethod(EnableSession = true)] // optional, but usually forgotten
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public bool MyMethod(int id)
        {
            return true;
        }
    

    另外,您还需要有 Content-rewrite 模块来处理前导回调参数:

    http://www.codeproject.com/Articles/43038/Accessing-Remote-ASP-NET-Web-Services-Using-JSONP

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 2014-10-04
      • 2022-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多