转自:西北小强 的 《java+jQuery解决ajax跨域小demo》
原址:https://yuxisanren.iteye.com/blog/2019666
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",多个域名直接用“,”分开;
b、由于IE8-IE10不支持通过设置Access-Control-Allow-Origin头的方式,所以对于IE需要按照IE提供的方案使用XDomainRequest对象解决,
详情http://msdn.microsoft.com/en-us/library/ie/cc288060(v=vs.85).aspx
2、服务端以js代码的方式给前台返回数据
前台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();
}