1、在服务端设置请求头信息
前台JS代码: $("#but4").click(function(){ var vesion=parseInt($.browser.version); if($.browser.msie && vesion>=8 && vesion<11){//判断浏览器版本是否为IE xdr = new XDomainRequest(); xdr.open("POST", "http://shop.weibaobei.com/test1/test1!getAjaxData.action?type=IE"); xdr.send(); xdr.onload=function(){ alert("返回结果:"+xdr.responseText); } }else{ $.ajax({ url:'http://shop.weibaobei.com/test1/test1!getAjaxData.action', type:'post', data:{random:Math.random()}, success:function(data){ alert(data); } }); } }); 后台java代码: public void getAjaxData() throws IOException{ PrintWriter out = this.getResponse().getWriter(); this.getResponse().setContentType("text/html;charset=UTF-8"); this.getResponse().addHeader("Access-Control-Allow-Origin","*");//'*'表示允许所有域名访问,可以设置为指定域名访问,多个域名中间用','隔开 //如果IE浏览器则设置头信息如下 if("IE".equals(this.getRequest().getParameter("type"))){ this.getResponse().addHeader("XDomainRequestAllowed","1"); } out.print("success"); out.close(); } |
a、在使用此方法时在后端为了安全起见最好设置允许那些域进行跨域访问,如“shop.weibaobei.com",多个域名直接用“,”分开;
前台JS代码: $("#but6").click(function(){ $.getScript('http://shop.weibaobei.com/test1/test1!getJavaScriptData.action',function(){ //前台获取后台返回数据 alert(a); alert(remote.test); }); }); 后台java代码: public void getJavaScriptData() throws IOException{ PrintWriter out = this.getResponse().getWriter(); this.getResponse().setContentType("text/html;charset=UTF-8"); out.print("var s=23; var a='444'; var f=[2,1];var remote={test:'hello'}; ");//给前台返回js代码 out.close(); } |