support JSONP returns in ASP.NET

二次信任 提交于 2020-01-06 09:55:27

问题


how to support JSONP returns in ASP.Net website for getJson calls?

var url = "http://demo.dreamacc.com/TextTable.json?callback=?";
        $.ajax({
            type: 'GET',
            url: url,
            async: false,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function (ooo) {
                alert('hi');
                alert(ooo);
            },
            error: function () {
                alert('w');
            }
        });

the previous function doesn't fire the neither the success nor the error function


回答1:


On the server you could write a handler which will return JSONP response:

public class MyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // set the response content type to application/json
        context.Response.ContentType = "application/json";

        // generate some JSON that we would like to return to the client
        string json = new JavaScriptSerializer().Serialize(new
        {
            status = "success"
        });

        // get the callback query string parameter
        var callback = context.Request["callback"];
        if (!string.IsNullOrEmpty(callback))
        {
            // if the callback parameter is present wrap the JSON
            // into this parameter => convert to JSONP
            json = string.Format("{0}({1})", callback, json);
        }

        // write the JSON/JSONP to the response
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

The idea here is that the generic handler will check for the presence of a callback querystring parameter and if specified it will wrap the JSON into this callback.

Now you could point the $.ajax call to this server side handler:

var url = "http://demo.dreamacc.com/MyHandler";
$.ajax({
    type: 'GET',
    url: url,
    jsonp: 'callback',
    dataType: 'jsonp',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function (result) {
        alert(result.success);
    },
    error: function () {
        alert('error');
    }
});


来源:https://stackoverflow.com/questions/14673725/support-jsonp-returns-in-asp-net

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