【问题标题】:support JSONP returns in ASP.NET支持 ASP.NET 中的 JSONP 返回
【发布时间】:2013-01-18 09:13:25
【问题描述】:

如何在 ASP.Net 网站中支持 JSONP 返回 getJson 调用?

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');
            }
        });

前一个函数不会触发成功和错误函数

【问题讨论】:

    标签: jquery jsonp getjson


    【解决方案1】:

    您可以在服务器上编写一个返回 JSONP 响应的处理程序:

    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; }
        }
    }
    

    这里的想法是通用处理程序将检查是否存在 callback 查询字符串参数,如果指定,它将 JSON 包装到此回调中。

    现在您可以将 $.ajax 调用指向此服务器端处理程序:

    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');
        }
    });
    

    【讨论】:

    • 这个网址正确吗? var url = "demo.dreamacc.com/MyHandler";到哪里去读取这个文件 var url = "demo.dreamacc.com/TextTable.json?callback=?"
    • 我的答案中的 url 现在指向您需要在服务器上编写以支持 JSONP 的通用处理程序。如果服务器不支持 JSONP,则不能从客户端调用中使用它。所以你需要做的第一件事就是在服务器上添加对 JSONP 的支持。
    • 如果域名不同,记得在通话中添加CORS支持($.support.cors = true;)。
    • 我添加了处理程序,当指向它或我需要读取的文件时,我没有收到任何响应,既没有成功也没有失败。
    • @balexandre,JSONP 的全部意义在于您不需要 CORS。
    猜你喜欢
    • 2013-06-24
    • 1970-01-01
    • 2011-04-11
    • 2013-05-07
    • 2017-02-13
    • 2014-05-07
    • 1970-01-01
    • 2013-08-26
    • 2016-09-03
    相关资源
    最近更新 更多