Ajax跨域实现代码(后台jsp)
AJAX教程
AJAX=AsynchronousJavaScriptandXML(异步的JavaScript和XML)。
在应用时主要是创建XMLHttpRequest对象,调用指定服务地址。
但是IE中各个版本支持的不太一样,所以在创建次对象时可能要特殊处理下。
一般如下:
functioncreateXMLHttpRequest(){
varxmlhttp;
try{
xmlhttp=newXMLHttpRequest();//ie7及以上,其他浏览器
}catch(e){
try{
xmlhttp=newActiveXObject("Msxml2.XMLHTTP");//ie6
}catch(e){
try{
xmlhttp=newActiveXObject("Microsoft.XMLHTTP");//ie6以下
}catch(e){
throw"创建AJAX对象失败!";
}
}
}
returnxmlhttp;
}
varxmlhttp=createXMLHttpRequest();
xmlhttp.open("GET","http://localhost:8080/SimpleBlog/AjaxTest",true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=function(result){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
alter(result.test);
}
};
但是浏览器再执行javascript代码时,有个著名的同源策略,这使得跨域请求就不是那么方便了。
那一般都是用什么方式支持跨域呢?
1、通过中间代理服务器,获取要跨域请求的数据。
2、通过iframe内嵌带请求域的页面,来解决跨域访问问题。
3、通过jsonp方式。
4、不过现在已经提出了XMLHttpRequestLevel2(XHR2)允许跨域请求,不过要在server的返回头中显示声明允许跨域请求(浏览器的支持情况:http://caniuse.com/#feat=xhr2)。
下面简单说下jsonp与xtr2。
jsonp:
jsonp简单的说就是利用<script>标签来实现跨域请求的调用,因为浏览器中脚本的加载是不受同源策略影响的。
functionget(){
varurl='http://localhost:8080/SimpleBlog/AjaxTest?callback=callback';
varscript=document.createElement('script');
script.setAttribute("type","text/javascript");
script.src=url;
document.body.appendChild(script);
}
functioncallback(va){
alert(va.test);
}
服务端(java):
booleanjsonP=false;
Stringcb=this.request.getParameter("callback");
if(cb!=null){
jsonP=true;
response.setContentType("text/javascript");
}else{
response.setContentType("application/x-json");
}
PrintWriterout=response.getWriter();
if(jsonP){
try{
out.println(cb+"({\"test\":\"1\"})");
out.flush();
out.close();
}catch(Exceptione){
throwe;
}
}
这样就可以实现跨域调用了。
而我们经常用的jquery已经实现了此类方式的封装,使用起来更简单。
$(document).ready(function(){
$('#jqueryajax').bind('click',function(){
$.ajax({
type:'get',
async:false,
url:'http://localhost:8080/SimpleBlog/AjaxTest1',
dataType:'jsonp',
jsonp:'callback',
success:function(json){
alert(json.result);
},
error:function(){
alert('fail');
}
});
});
});
服务端(java):
我用了struts是这样写的:
publicclassAjaxTest1extendsActionSupport{
privateStringresult;
publicStringgetResult(){
returnresult;
}
publicStringexecute(){
this.result="1";
return"jqueryajax";
}
}
配置文件:
<actionname="AjaxTest1"class="AjaxTest1"> <resultname="jqueryajax"type="json"> <paramname="callbackParameter">callback</param> </result> </action>
下面说说xtr2:
这个就更简单了,直接创建调用即可。
functioncreateCORSRequest(method,url){
varxhr=newXMLHttpRequest();
if('withCredentials'inxhr){
xhr.open(method,url,true);
}elseif(typeofXDomainRequest!='undefined'){
xhr=newXDomainRequest();
xhr.open(method,url);
}else{
xhr=null;
}
returnxhr;
}
functionxhr2(){
varrequest=createCORSRequest('GET','http://localhost:8080/SimpleBlog/AjaxTest1');
if(request){
request.onload=function(){
alert(request.responseText);
}
request.onerror=function(e){
alert('error');
}
request.send();
}
}
服务端:其实只要在返回response中设置
httpResponse.addHeader("Access-Control-Allow-Origin","*");
即可。