Ajax cross-origin implementation code (backend jsp) and ajaxjsp

Source: Internet
Author: User

Ajax cross-origin implementation code (backend jsp) and ajaxjsp

AJAX tutorial

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

When an application is used, it mainly creates an XMLHttpRequest object and calls the specified service address.

However, each version of IE does not support the same features. Therefore, you may need to perform special operations when creating an object.

Generally:

Function createXMLHttpRequest () {var xmlhttp; try {xmlhttp = new XMLHttpRequest (); // ie7 and later, other browsers} catch (e) {try {xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP"); // ie6} catch (e) {try {xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP "); // ie6 or lower} catch (e) {throw" An error occurred while creating the AJAX object! ";}}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 );}};

However, when the Browser executes javascript code again, there is a well-known same-origin policy, which makes cross-origin requests less convenient.

In general, how does one support cross-origin?

1. Use the intermediate proxy server to obtain data for cross-origin requests.

2. Use iframe to embed pages with request domains to solve cross-origin access problems.

3. jsonp.

4. But now XMLHttpRequest Level2 (XHR2) has been proposed to allow cross-origin requests, but it is necessary to display the declaration in the server's return header to allow cross-origin requests (Browser support: http://caniuse.com/#feat=xhr2 ).

Let's briefly describe jsonp and xtr2.

Jsonp:

In short, jsonp uses the <script> tag to call cross-origin requests, because the script Loading in the browser is not affected by the same-origin policy.

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-origin calls can be implemented.

Jquery, which we often use, has implemented the encapsulation of this method, making it easier 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 it like this:

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

Configuration file:

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

The following describes xtr2:

This is simpler, just create a call.

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, you only need to set in response
HttpResponse. addHeader ("Access-Control-Allow-Origin ","*");
You can.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.