views:

119

answers:

2

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?

A: 

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: http://stackoverflow.com/questions/2948628/asp-net-passing-json-from-jquery-to-ashx for info. There are some good code examples to show you what to do.

Chris Lively
Sorry, but that wasn't helpful at all.
Bigglesby
A: 

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