3

JavaScript Cross-Browser Cross-Domain XMLHttpRequest (XDomainRequest in IE)

 2 years ago
source link: http://siongui.github.io/2012/09/25/javascript-cors-xmlhttprequest/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript Cross-Browser Cross-Domain XMLHttpRequest (XDomainRequest in IE)

Updated: March 20, 2017

This post gives a client-side sample code for very useful technique in AJAX programming: Cross-Domain, Cross-Browser XMLHttpRequest requests (XDomainRequest for IE8+).

Before doing Cross-Domain AJAX requests, Cross-Origin Resource Sharing (CORS) must be enabled on servers first. Visit Enable CORS website to see how to enable CORS on your server.

Demo

Source Code for Demo (HTML):

crossDomainXHR.html | repository | view raw

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Cross-Browser Cross-Domain XMLHttpRequest (XDomainRequest in IE) Example</title>
</head>
<body>

<button id="bt" type="button">Click Me to Issue Cross-Domain XHR!</button>

<script src="xhr.js"></script>
</body>
</html>

Source Code for Demo (JavaScript):

xhr.js | repository | view raw

/**
 * Cross-Browser Cross-Domain XMLHttpRequest (XDomainRequest in IE)
 *
 * @param {string} url The url of HTTP GET (AJAX) request.
 * @param {function} callback The callback function if the request succeeds.
 * @param {function} failCallback The callback function if the request fails.
 */
AJAXRequest = function(url, callback, failCallback) {
  var xmlhttp = new XMLHttpRequest();

  // @see http://blogs.msdn.com/b/ie/archive/2012/02/09/cors-for-xhr-in-ie10.aspx
  // @see http://bionicspirit.com/blog/2011/03/24/cross-domain-requests.html
  // @see http://msdn.microsoft.com/en-us/library/ie/cc288060(v=vs.85).aspx
  if ("withCredentials" in xmlhttp) {
    // for Chrome, Firefox, Opera
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200 || xmlhttp.status == 304) {
          callback(xmlhttp.responseText);
        } else {
          setTimeout(failCallback, 0);
        }
      }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
  } else {
    // for IE
    var xdr = new XDomainRequest();
    xdr.onerror = function(){setTimeout(failCallback, 0);};
    xdr.ontimeout = function(){setTimeout(failCallback, 0);};
    xdr.onload = function() {
      callback(xdr.responseText);
    };

    xdr.open("get", url);
    xdr.send();
  }
};

/**
 * Callback function of AJAX request if the request succeeds.
 */
callback = function(responseText) {
  // write your own handler here.
  alert('result from https://golden-operator-130720.appspot.com/sukhada.json\n' + responseText);
};

/**
 * Callback function of AJAX request if the request fails.
 */
failCallback = function() {
  // write your own failure handler here.
  alert('AJAXRequest failure!');
};


document.getElementById('bt').onclick = function() {
  AJAXRequest('https://golden-operator-130720.appspot.com/sukhada.json', callback, failCallback);
};

The AJAXRequest function provides the Cross-Domain, Cross-Browser XHR. Put the function in your code and re-write the content of callback and failCallback to fit your needs.

If you web page is served via HTTPS, the server that returns data also needs to serve via HTTPS. Otherwise browsers will block the request and make the request fail.


Tested on: Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)


References:

[1]CORS for XHR in IE10

[2]Cross-Domain, Cross-Browser AJAX Requests

[3]XDomainRequest object

[4]enable cross-origin resource sharing


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK