码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2014-12-11 13:59:45      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

直接上最后的结果吧

JS:

bubuko.com,布布扣
 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一般处理程序):

bubuko.com,布布扣
 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

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

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/doscanner/p/4157401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!