温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Ajax跨域实现代码(后台jsp)

发布时间:2020-10-03 16:19:58 来源:脚本之家 阅读:174 作者:mdxy-dxy 栏目:web开发

AJAX 教程

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

在应用时主要是创建XMLHttpRequest对象,调用指定服务地址。

但是IE中各个版本支持的不太一样,所以在创建次对象时可能要特殊处理下。

一般如下:

function createXMLHttpRequest(){
 var xmlhttp;
 try{
  xmlhttp = new XMLHttpRequest();//ie7及以上,其他浏览器
 }catch(e){
  try{
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");//ie6
  }catch(e){
   try{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//ie6以下
   }catch(e){
    throw "创建AJAX对象失败!";
   }
  }
 }
 return xmlhttp;
 }


 var xmlhttp = 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、不过现在已经提出了XMLHttpRequest Level2(XHR2)允许跨域请求,不过要在server的返回头中显示声明允许跨域请求(浏览器的支持情况:http://caniuse.com/#feat=xhr2)。

下面简单说下jsonp与xtr2。

jsonp:

jsonp简单的说就是利用<script>标签来实现跨域请求的调用,因为浏览器中脚本的加载是不受同源策略影响的。

function get() {
  var url = 'http://localhost:8080/SimpleBlog/AjaxTest?callback=callback';
  var script = document.createElement('script'); 
  script.setAttribute("type","text/javascript"); 
  script.src = url; 
  document.body.appendChild(script); 
 }
 
 function callback(va){
  alert(va.test);
 }

服务端(java):

 boolean jsonP = false;
 String cb = this.request.getParameter("callback");
 if (cb != null) {
 jsonP = true;
 response.setContentType("text/javascript");
 } else {
  response.setContentType("application/x-json");
 }
 PrintWriter out = response.getWriter();
 if (jsonP) {
  try {
   out.println(cb + "({\"test\":\"1\"})");
   out.flush();
   out.close();
  } catch (Exception e) {
   throw e;
  }
 }

这样就可以实现跨域调用了。

而我们经常用的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是这样写的:

public class AjaxTest1 extends ActionSupport {

 private String result;
 public String getResult() {
  return result;
 }
 
 public String execute() {
 
  this.result = "1";
  return "jqueryajax";
 }
}

配置文件:

<action name="AjaxTest1" class="AjaxTest1">
 <result name="jqueryajax" type="json">
  <param name="callbackParameter">callback</param>
 </result>
 </action>

下面说说xtr2:

这个就更简单了,直接创建调用即可。

function createCORSRequest(method,url){
  var xhr=new XMLHttpRequest();
  if('withCredentials' in xhr){
  xhr.open(method,url,true);
  }else if(typeof XDomainRequest!='undefined'){
   xhr=new XDomainRequest(); 
   xhr.open(method,url);
  }else{
   xhr=null;
  }
  return xhr;
 }
 
 function xhr2(){
  var request=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", "*");
即可。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI