【问题标题】:Cross Domain Access to ashx service using jQuery使用 jQuery 跨域访问 ashx 服务
【发布时间】:2011-12-03 04:20:14
【问题描述】:

我有一个 ASP.NET 服务,我可以从一个返回 JSON 字符串的 asxh 文件访问它。该服务运行良好,除非从我们位于单独服务器上的博客子域访问。 (blog.laptopmag.com)

这是我的 jQuery

    $.ajax({
        type: "GET",
        url: "http://www.laptopmag.com/scripts/service.ashx",
        data: { "op": "get_products" },
        dataType: "json",
        success: function (data) {
            alert(data);
        }
    });

这是我的 ashx 文件

public class service : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        string jsonStr = "{}";
        string op = context.Request["op"];

        // Process request

        context.Response.ContentType = "application/json";
        context.Response.Write(jsonStr);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

我尝试过切换到 jsonp 请求,但一定是做错了什么,因为我什么都做不了。这是我尝试过的。

这是我的 jsonp 尝试,从 blog.laptopmag.com 调用时似乎不起作用

$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=ProcessRequest&op=get_products', function(json) { 
    console.log(json);
  });

【问题讨论】:

    标签: asp.net jquery


    【解决方案1】:

    好的,感谢以下帖子,我发现了 JSONP 请求的问题所在: Jquery success function not firing using JSONP

    问题是请求没有得到预期格式的响应。

    现在,我的 ashx 文件如下所示:

    public void ProcessRequest (HttpContext context) {
            string jsonStr = "{}";
            string op = context.Request["op"];
            string jsonp = context.Request["callback"];
    
            // Do something here
    
            if (!String.IsNullOrEmpty(jsonp))
            {
                jsonStr = jsonp + "(" + jsonStr + ")";
            }
    
            context.Response.ContentType = "application/json";
            context.Response.Write(jsonStr);
        }
    

    jQuery ajax 请求如下所示:

    $.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=?&op=get_products', function(json) { 
        console.log(json);
      });
    

    【讨论】:

      【解决方案2】:

      安全限制阻止您进行跨域 jquery ajax 调用,但有一些变通方法。 IMO 最简单的方法是在您的站点上创建一个充当代理的页面,并使用您的 jquery 请求访问该页面。在您的代理的 page_load 中:

      WebClient client = new WebClient ();
      Response.Write (client.DownloadString ("your-webservice-url"));
      

      其他解决方案可以通过quick Google search.找到

      【讨论】:

      • 我得到的只是一个以 HTML/Text 格式公开的实际服务的页面。我想我需要更多帮助
      猜你喜欢
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 2013-05-15
      • 2011-05-24
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多