AJAX的跨域訪問-兩種有效解決方案介紹_PHP教程

來源:互聯網
上載者:User
新的W3C策略實現了HTTP跨域訪問,還虧我找了很久的資料解決這個問題:
只需要在servlet中返回的頭部資訊中添加Access-Control-Allow-Origin這個既可。
比如我要開放所有我本地的跨域訪問,就設定如下:response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
這樣我本地的A工程中的AJAX請求就可以跨域請求B工程中的servlet。
代碼如下:
HTML的JS的ajax請求:
複製代碼 代碼如下:
/* 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);
}
}
}

代碼在本機測試是可以的,待過兩天,我把servlet放到伺服器上去,然後再本地測試。
上面的方式雖然很完美的解決了問題,但是上面的文章也說了。可能存在安全問題,而且新標準是否都支援還是個問題,所以我們可以套用另外一種取巧的方式來完成同樣的效果,因為js不存在跨域問題,如果我們伺服器的servlet返回的是JS指令碼,那就可以了。我們可以在A工程的js中使用javascript的src來訪問B工程的servlet,然後通過servlet輸出的js指令碼來傳遞資料。因此根據這個思想我又做了下面代碼的測試:
頁面的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這個函數是反調函數。servlet代碼中會使用eval這種方式來執行。
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());
}
}
}

http://www.bkjia.com/PHPjc/327758.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/327758.htmlTechArticle新的W3C策略實現了HTTP跨域訪問,還虧我找了很久的資料解決這個問題: 只需要在servlet中返回的頭部資訊中添加 Access-Control-Allow-Origin 這個既...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.