AJAX의 도메인 간 액세스 - 두 가지 효과적인 해결 방법 소개

새로운 W3C 정책은 HTTP 크로스 도메인 접근을 실현했고 제가 오랫동안 이 문제를 해결한 덕분입니다. servlet에서 되돌아오는 머리 정보에 Access-Control-Allow-Origin을 추가하면 됩니다.예를 들어 나는 로컬의 전역 접근을 모두 개방하려고 하는데, 다음과 같이 설정한다:response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*"), 이렇게 하면 내 로컬 A 프로젝트의 AJAX 요청이 B 프로젝트의 서브렛을 도메인 간에 요청할 수 있습니다. 코드는 다음과 같습니다. 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);
서브렛 코드:

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());
}
}
}

좋은 웹페이지 즐겨찾기