解决jQuery ajax跨域问题,Google、IE、Firefox亲测有效

直接上最后的结果吧

JS:

 1 $.ajax({
 2             type: "GET",
 3             async: false,
 4             crossDomain: true,
 5             url: "www.test.com/TestHandler.ashx",
 6             data: { Id: "1"},
 7             dataType: "jsonp",
 8             jsonp: "callback",
 9             jsonpCallback: "callbackHandler",
10             success: function (data) {
11                 //success
12             },
13             error: function (x, status, error) {
14                 //error
15             }
16         });
View Code

服务端(这里我用的是ashx一般处理程序):

 1 public void ProcessRequest(HttpContext context)
 2         {
 3             JavaScriptSerializer jsonHelper = new JavaScriptSerializer();
 4 
 5             HttpContext.Current.Response.ContentType = "application/json";
 6             HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
 7             HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, Content-Type,Authorization, Accept, X-Requested-With");
 8             HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
 9 
10             var list=数据;
11             
12             if (string.IsNullOrEmpty(context.Request["callback"]))
13             {
14                 context.Response.Write(jsonHelper.Serialize(list));
15             }
16             else
17             {
18                 context.Response.Write(string.Format("{0}({1})", context.Request["callback"], jsonHelper.Serialize(list)));
19             }
20         }
View Code
posted @ 2014-12-11 13:32  doscanner  阅读(624)  评论(1编辑  收藏  举报