ASP.NET Generic HTTP Handler (.ashx) supporting JSONP

扶醉桌前 提交于 2019-12-10 10:25:25

问题


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?


回答1:


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

    });
});



回答2:


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.



来源:https://stackoverflow.com/questions/3702959/asp-net-generic-http-handler-ashx-supporting-jsonp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!