Ajax cross domain implementation code of background jsp

  • 2021-07-13 04:15:03
  • OfStack

AJAX Tutorial

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

In application, it mainly creates XMLHttpRequest object and calls the specified service address.

However, IE versions do not support 1, so the creation of secondary objects may require special processing.

1 as follows:


function createXMLHttpRequest(){
 var xmlhttp;
 try{
  xmlhttp = new XMLHttpRequest();//ie7 And above, other browsers 
 }catch(e){
  try{
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");//ie6
  }catch(e){
   try{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//ie6 The following 
   }catch(e){
    throw " Create AJAX Object failed! ";
   }
  }
 }
 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);
  }
 };

But when the browser executes javascript code again, there is a famous homology policy, which makes cross-domain requests less convenient.

What are the ways to support cross-domains?

1. Obtain the data to be requested across domains through the intermediate proxy server.

2. A page with request domain is embedded in iframe to solve the problem of cross-domain access.

3. Through jsonp mode.

4. However, it has been proposed that XMLHttpRequest Level2 (XHR2) allow cross-domain requests, but the declaration that cross-domain requests are allowed should be displayed in the return header of server (browser support: http://caniuse.com/# feat=xhr2).

Let's briefly talk about jsonp and xtr2.

jsonp:

jsonp is simply to use < script > Tag to implement the invocation of cross-domain requests, because the loading of scripts in browsers is not affected by homology policies.


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

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

In this way, cross-domain calls can be realized.

However, jquery, which we often use, has already implemented this kind of encapsulation, which is simpler to use.


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

Server (java):
I used struts to write this:


public class AjaxTest1 extends ActionSupport {

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

Profile:


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

Let's talk about xtr2:

This is even simpler, just create the call directly.


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

Server: In fact, it only needs to be set in the return response
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
That's enough.


Related articles: