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());
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
AJAX의 도메인 간 액세스 - 두 가지 효과적인 해결 방법 소개새로운 W3C 정책은 HTTP 크로스 도메인 접근을 실현했고 제가 오랫동안 이 문제를 해결한 덕분입니다. servlet에서 되돌아오는 머리 정보에 Access-Control-Allow-Origin을 추가하면 됩니다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.