//.net 后端代码 public void ProcessRequest(HttpContext context) { string oldurl = SysCommon.GetQueryStrString("oldurl");//原接口 if (!string.IsNullOrEmpty(oldurl)) { string forms = context.Request.Form.ToString(); string[] keys = context.Request.Form.AllKeys; System.Text.StringBuilder str = new System.Text.StringBuilder(); foreach (string key in keys) str.Append(key + "=" + context.Request.Form.GetValues(key)[0] + "&"); Maticsoft.Common.WebClient wc = new Maticsoft.Common.WebClient(); wc.Encoding = System.Text.Encoding.UTF8; string result = wc.Post(oldurl, str.ToString().TrimEnd('&')); context.Response.Write(result); } else context.Response.Write("oldurl is empty!"); }
<script> //获取跨域URL function getCrossDomainPostUrl(currURL) { //如果是跨域才走这个里处理 if ((currURL.indexOf("http") == 0 || currURL.indexOf("//") == 0) && currURL.indexOf(location.host) == -1) { var isIELower = false; try { isIELower = navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE", "")) <= 9; } catch (e) { } if (isIELower) { console.log("您的浏览器版本过低,请使用IE9及以上版本"); if (currURL.indexOf("//") == 0 && currURL.indexOf("bidcenter.com.cn") > 0) currURL = "http:" + currURL; return "CrossDomainPostUrl.ashx?oldurl=" + encodeURIComponent(currURL); } } return currURL; } //网站端代码 var datas = { id: 123, name: "张生" } $.ajax({ type: "POST", data: datas, url: getCrossDomainPostUrl("http://www.test.com.cn/testr.ashx"), dataType: "text", success: function (data) { alert(data); }, error: function (e) { alert(e); } }); </script>
说明:
1.http://www.test.com.cn/testr.ashx 这个是实际要访问的跨域页面
2.CrossDomainPostUrl.ashx 这是当前站点儿下的一个后台中转页面
优点:
1.兼容所有IE
2.JS、中转页面都是公共的,所有跨域位置都可使用
缺点:
1.如果验证来源网站的域名慎用,因为通过这个接口全都是当前域名访问了
2.所有数据通过当前站点儿返回,会增加当前站点儿流量。 所以有优点也有缺点,自己考虑用不用吧,反正是解决了我的问题,分享 给大家。