3

Can someone show an example of an HTTP Handler that returns JSON and supports cross domain calls. I am using jQuery's getJSON() that sends a request to an .ashx file on my web server.

I understand that I need to add ?callback=? to my url in the getJSON() url, but I'm not sure what needs to be done on the server in my ashx file?

Bigglesby
  • 251
  • 3
  • 10

2 Answers2

10

Figured it out. I added this function to my handler and called it:

void WriteCallback(HttpContext context, string json)
        {
            context.Response.Write(string.Format("{0}({1});", context.Request["callback"], json));
        }

Then in the browser:

$(function () {
    $.getJSON('MyHandler.ashx?callback=?', { Foo: "Bar" }, function (data) {

        if (data.SomeCondition)
            $('#someElement').show();

    });
});
Bigglesby
  • 251
  • 3
  • 10
  • +1 For the first function - saved me some time today while doing this. – James Skemp Mar 10 '11 at 23:20
  • Thank you! I've been banging my head against the wall all day and didn't realize you had to wrap the JSON output with the callback function name when doing JSONP calls. – dgundersen Jul 14 '11 at 21:27
1

The only way "cross domain" could potentially become an issue is if you are using some sort of state mechanism (ie: cookies) as part of the call. Which you shouldn't do.

Otherwise, see the this link: ASP.NET - Passing JSON from jQuery to ASHX for info. There are some good code examples to show you what to do.

Community
  • 1
  • 1
NotMe
  • 87,343
  • 27
  • 171
  • 245