解决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 });
服务端(这里我用的是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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。