轉自:西北小強 的 《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();
}