AJAX的跨域訪問-兩種有效的解決方法介紹
更新時(shí)間:2013年06月22日 15:00:51 作者:
本篇文章是對(duì)AJAX的跨域訪問-兩種有效的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
新的W3C策略實(shí)現(xiàn)了HTTP跨域訪問,還虧我找了很久的資料解決這個(gè)問題:
只需要在servlet中返回的頭部信息中添加Access-Control-Allow-Origin這個(gè)既可。
比如我要開放所有我本地的跨域訪問,就設(shè)置如下:response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
這樣我本地的A工程中的AJAX請(qǐng)求就可以跨域請(qǐng)求B工程中的servlet。
代碼如下:
HTML的JS的ajax請(qǐng)求:
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
var url = "http://127.0.0.1:2012/esb/servlet/HttpClient?randomType=MIX";
xmlHttp.open("GET", url, true);
//Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
alert(response);
}
}
//Send the request
xmlHttp.send(null);
servlet代碼:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
//下面那句是核心
resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
resp.setDateHeader("Expires", 0);
ServletOutputStream sos = resp.getOutputStream();
try {
sos.write(obj.toString().getBytes("GBK"));
} catch (Exception e) {
System.out.println(e.toString90)
} finally {
try {
sos.close();
} catch (Exception e) {
LOG.error(e);
}
}
}
代碼在本機(jī)測(cè)試是可以的,待過兩天,我把servlet放到服務(wù)器上去,然后再本地測(cè)試。
上面的方式雖然很完美的解決了問題,但是上面的文章也說了??赡艽嬖诎踩珕栴},而且新標(biāo)準(zhǔn)是否都支持還是個(gè)問題,所以我們可以套用另外一種取巧的方式來完成同樣的效果,因?yàn)閖s不存在跨域問題,如果我們服務(wù)器的servlet返回的是JS腳本,那就可以了。我們可以在A工程的js中使用javascript的src來訪問B工程的servlet,然后通過servlet輸出的js腳本來傳遞數(shù)據(jù)。因此根據(jù)這個(gè)思想我又做了下面代碼的測(cè)試:
頁(yè)面的JS代碼:
function loadAjax(){
id="testesbscript";
oScript = document.getElementById(id);
var head = document.getElementsByTagName("head").item(0);
if (oScript) {
head.removeChild(oScript);
}
oScript = document.createElement("script");
var url = "http://127.0.0.1:2012/esb/servlet/HttpClient?randomType=MIX&success=justHandle
oScript.setAttribute("id",id);
oScript.setAttribute("type","text/javascript");
oScript.setAttribute("language","javascript");
head.appendChild(oScript);
}
//jsutHandle這個(gè)函數(shù)是反調(diào)函數(shù)。servlet代碼中會(huì)使用eval這種方式來執(zhí)行。
function justHandle(dd){
alert(dd);
}
servlet的代碼:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
Object obj = "test";
ServletOutputStream sos = resp.getOutputStream();
StringBuffer sb = new StringBuffer();
resp.setCharacterEncoding("GBK");
resp.setHeader("Charset","GBK");
resp.setContentType("charset=GBK");
//下面那句表明是javascript腳本文件
resp.setContentType("text/javascript");
sb.append("eval(/""+paramMap.get("success")+"(/'"+obj.toString()+"/')/")");
try {
sos.write(sb.toString().getBytes(this.character_encoding));
} catch (Exception e) {
System.out.println(e.toString());
} finally {
try {
sos.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
只需要在servlet中返回的頭部信息中添加Access-Control-Allow-Origin這個(gè)既可。
比如我要開放所有我本地的跨域訪問,就設(shè)置如下:response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
這樣我本地的A工程中的AJAX請(qǐng)求就可以跨域請(qǐng)求B工程中的servlet。
代碼如下:
HTML的JS的ajax請(qǐng)求:
復(fù)制代碼 代碼如下:
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
var url = "http://127.0.0.1:2012/esb/servlet/HttpClient?randomType=MIX";
xmlHttp.open("GET", url, true);
//Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
alert(response);
}
}
//Send the request
xmlHttp.send(null);
servlet代碼:
復(fù)制代碼 代碼如下:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
//下面那句是核心
resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
resp.setDateHeader("Expires", 0);
ServletOutputStream sos = resp.getOutputStream();
try {
sos.write(obj.toString().getBytes("GBK"));
} catch (Exception e) {
System.out.println(e.toString90)
} finally {
try {
sos.close();
} catch (Exception e) {
LOG.error(e);
}
}
}
代碼在本機(jī)測(cè)試是可以的,待過兩天,我把servlet放到服務(wù)器上去,然后再本地測(cè)試。
上面的方式雖然很完美的解決了問題,但是上面的文章也說了??赡艽嬖诎踩珕栴},而且新標(biāo)準(zhǔn)是否都支持還是個(gè)問題,所以我們可以套用另外一種取巧的方式來完成同樣的效果,因?yàn)閖s不存在跨域問題,如果我們服務(wù)器的servlet返回的是JS腳本,那就可以了。我們可以在A工程的js中使用javascript的src來訪問B工程的servlet,然后通過servlet輸出的js腳本來傳遞數(shù)據(jù)。因此根據(jù)這個(gè)思想我又做了下面代碼的測(cè)試:
頁(yè)面的JS代碼:
復(fù)制代碼 代碼如下:
function loadAjax(){
id="testesbscript";
oScript = document.getElementById(id);
var head = document.getElementsByTagName("head").item(0);
if (oScript) {
head.removeChild(oScript);
}
oScript = document.createElement("script");
var url = "http://127.0.0.1:2012/esb/servlet/HttpClient?randomType=MIX&success=justHandle
oScript.setAttribute("id",id);
oScript.setAttribute("type","text/javascript");
oScript.setAttribute("language","javascript");
head.appendChild(oScript);
}
//jsutHandle這個(gè)函數(shù)是反調(diào)函數(shù)。servlet代碼中會(huì)使用eval這種方式來執(zhí)行。
function justHandle(dd){
alert(dd);
}
servlet的代碼:
復(fù)制代碼 代碼如下:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
Object obj = "test";
ServletOutputStream sos = resp.getOutputStream();
StringBuffer sb = new StringBuffer();
resp.setCharacterEncoding("GBK");
resp.setHeader("Charset","GBK");
resp.setContentType("charset=GBK");
//下面那句表明是javascript腳本文件
resp.setContentType("text/javascript");
sb.append("eval(/""+paramMap.get("success")+"(/'"+obj.toString()+"/')/")");
try {
sos.write(sb.toString().getBytes(this.character_encoding));
} catch (Exception e) {
System.out.println(e.toString());
} finally {
try {
sos.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
您可能感興趣的文章:
- 完美解決AJAX跨域問題
- Ajax實(shí)現(xiàn)跨域訪問的三種方法
- AJAX跨域請(qǐng)求json數(shù)據(jù)的實(shí)現(xiàn)方法
- Ajax 設(shè)置Access-Control-Allow-Origin實(shí)現(xiàn)跨域訪問
- IE9版本以下ajax 跨域問題可行解決方法
- 解決AJAX中跨域訪問出現(xiàn)''沒有權(quán)限''的錯(cuò)誤
- Nginx服務(wù)器中處理AJAX跨域請(qǐng)求的配置方法講解
- 解決ajax跨域請(qǐng)求數(shù)據(jù)cookie丟失問題
- 完美解決ajax跨域請(qǐng)求下parsererror的錯(cuò)誤
- 關(guān)于Ajax跨域問題及解決方案詳析
相關(guān)文章
php使用PDO從數(shù)據(jù)庫(kù)表中讀取數(shù)據(jù)的實(shí)現(xiàn)方法(必看)
下面小編就為大家?guī)硪黄猵hp使用PDO從數(shù)據(jù)庫(kù)表中讀取數(shù)據(jù)的實(shí)現(xiàn)方法(必看)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06Laravel實(shí)現(xiàn)隊(duì)列的示例代碼
這篇文章主要為大家詳細(xì)介紹了Laravel實(shí)現(xiàn)隊(duì)列的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)和借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)游戲2023-02-02shell腳本作為保證PHP腳本不掛掉的守護(hù)進(jìn)程實(shí)例分享
以下是對(duì)用shell腳本作為保證PHP腳本不掛掉的守護(hù)進(jìn)程實(shí)例進(jìn)行了分析介紹,需要的朋友可以參考下2013-07-07