开发者

Cross Domain Access to ashx service using jQuery

I have an ASP.NET service that I'm access from a asxh file that returns a JSON string. The service works great except when accessed from our blog sub domain which is on a separate server. (blog.laptopmag.com)

Here is my jQuery

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

and here is my ashx file

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 IsRe开发者_C百科usable {
        get {
            return false;
        }
    }
}

I've tried switching to a jsonp request, but must be doing something wrong because I can't get anything to pull back. Here is what I've tried.

and here is my jsonp attempt that doesn't seem to work when called from blog.laptopmag.com

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


OK, I figured out what the problem was with my JSONP request thanks to the following post: Jquery success function not firing using JSONP

The problem was that the request wasn't getting a response back in the expected format.

Now, my ashx file now looks like this:

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

and the jQuery ajax request looks like this:

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


Security restrictions prevent you from making cross-domain jquery ajax calls, but there are workarounds. IMO the easiest way is to create a page on your site that acts as a proxy and hit the page with your jquery request. In page_load of your proxy:

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

Other solutions can be found by a quick Google search.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜