这篇文章主要为大家详细介绍了解决AJAX的跨域访问-两种有效示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小玲来看看吧!
新的W3C策略实现了HTTP跨域访问,还亏我找了很久的资料解决这个问题:代码如下:
/* 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);
}
}
}
代码如下:
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);
}
代码如下:
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.q1010.com/173/15224-0.html
注:关于解决AJAX的跨域访问-两种有效示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。