Home  >  Article  >  Backend Development  >  AJAX cross-domain access - two effective solutions introduced_PHP tutorial

AJAX cross-domain access - two effective solutions introduced_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:04:29953browse

The new W3C policy implements HTTP cross-domain access. I have been looking for information for a long time to solve this problem:
Just add Access-Control-Allow-OriginThis is fine. For example, if I want to open all my local cross-domain access, I would set it as follows:
response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
In this way, the AJAX request in my local project A can cross-domain request the servlet in project B.

The code is as follows:
HTML JS ajax request:

Copy code The code is as follows :
/* 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 code:
Copy code The code is as follows:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
resp.setHeader("Pragma", "no-cache");
resp.setHeader ("Cache-Control", "no-cache");
//The following sentence is the core
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);
}
}
}

The code can be tested on this machine. It will be tested later. After two days, I put the servlet on the server and then tested it locally.
Although the above method perfectly solves the problem, the above article also said it. There may be security issues, and whether all new standards are supported is still a question, so we can use another tricky way to achieve the same effect, because js does not have cross-domain problems. If the servlet of our server returns a JS script, That's it. We can use the src of javascript in the js of project A to access the servlet of project B, and then pass the data through the js script output by the servlet. Therefore, based on this idea, I did the following code test: JS code of

page:
Copy code The code is as follows:
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);
}
//The jsutHandle function is a reverse function that is used in the servlet code.
function justHandle(dd){
alert(dd);
}


Servlet code:
Copy code The code is as follows:

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/327758.htmlTechArticle新的W3C策略实现了HTTP跨域访问,还亏我找了很久的资料解决这个问题: 只需要在servlet中返回的头部信息中添加 Access-Control-Allow-Origin 这个既...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn