Method of getting xmlhttp object by Ajax

Time:2020-10-30

This paper describes the method of getting xmlhttp object by Ajax. For your reference, the details are as follows:

XML HTTP object is used in Ajax. I have seen various writing methods to obtain this object, and I think this method is the most elegant. First of all, it considers that it is suitable for different browsers; secondly, it considers the priority loading order, and probes from the higher version to the lower version. Finally, if it is not found, an exception will be thrown.


function FactoryXMLHttpRequest() {
  if(window.XMLHttpRequest) {
    return new XMLHttpRequest();
  }else if(window.ActiveXObject) {
    var msxmls = new Array(
      'Msxml2.XMLHTTP.5.0',
      'Msxml2.XMLHTTP.4.0',
      'Msxml2.XMLHTTP.3.0',
      'Msxml2.XMLHTTP',
      'Microsoft.XMLHTTP');
    for (var i = 0; i < msxmls.length; i++) {
      try {
        return new ActiveXObject(msxmls[i]);
      } catch (e) {
      }
    }
  }
  throw new Error("Could not instantiate XMLHttpRequest");
}

I hope this article will be helpful to everyone’s Ajax programming.