ASP.NET Generic HTTP Handler (.ashx) supporting JSONP
Can so开发者_C百科meone 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?
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();
});
});
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.
精彩评论