ajax异域请求

来源:互联网 发布:手机怎么开通淘宝贷款 编辑:程序博客网 时间:2024/04/30 18:38

一、jsonp与jsonpCallback

1.客户端请求代码

 $.ajax(

                {
                    type: "get",
                    url: "http://domain/Handler.ashx",
                    dataType: "jsonp",
                    jsonpCallback: "cb",
                    success: function (data, textStatus, jqXHR) {
                        alert(data);
                    }, 
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("error");
                    }
                }

            )

2.服务端代码(一般处理程序Handler.ashx)

context.Response.ContentType = "text/plain";
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST");

context.Response.Write("cb(jsonstring)");
context.Response.End();


二、getJSON

1.客户端请求代码

 $.getJSON("http://domain/Handler.ashx?jsoncallback=?", function (data) {

            });

2.服务端代码(一般处理程序Handler.ashx)

context.Response.ContentType = "text/plain";
context.Response.Write(context.Request["jsoncallback"]+"(jsonstring)");
context.Response.End();


0 0
原创粉丝点击