SoFunction
Updated on 2025-03-01

Methods for implementing Ajax in native JavaScript

First, I will share with you the native JavaScript implementation Ajax code for your reference. The specific content is as follows

var getXmlHttpRequest = function() {
  if () {
    //Mainstream browsers provide XMLHttpRequest object    return new XMLHttpRequest();
  } else if () {
    //The lower version of IE browser does not provide XMLHttpRequest object    //So you must use the specific implementation of the IE browser, ActiveXObject,    return new ActiveXObject("");
  }

};
var xhr = getXmlHttpRequest();
 = function() {
  ();
  if ( === 3 &&  === 200) {
    //Execute the operation after successful acquisition    //The data is    ();
  }
};
("get", "", true);
("");

Below I will share with you several ways to implement native Ajax using JavaScript.
Before implementing ajax, you must create an XMLHttpRequest object. If the browser that creates this object is not supported, you need to create ActiveXObject. The specific method is as follows:

var xmlHttp; 
function createxmlHttpRequest() { 
if () { 
xmlHttp = new ActiveXObject(""); 
} else if () { 
xmlHttp=new XMLHttpRequest(); 
} 

(1) The following uses the xmlHttp created above to implement the simplest ajax get request:

function doGet(url){ 
// Note that when passing parameter values, it is best to use encodeURI to handle it to prevent garbled codecreatexmlHttpRequest(); 
("GET",url); 
(null); 
 = function() { 
if (( == 4) && ( == 200)) { 
alert('success'); 
} else { 
alert('fail'); 
} 
} 
} 

(2) Use the xmlHttp created above to implement the simplest ajax post request:

function doPost(url,data){ 
// Note that when passing parameter values, it is best to use encodeURI to handle it to prevent garbled codecreatexmlHttpRequest(); 
("POST",url); 
("Content-Type","application/x-www-form-urlencoded"); 
(data); 
 = function() { 
if (( == 4) && ( == 200)) { 
alert('success'); 
} else { 
alert('fail'); 
} 
} 
} 

The above is all about this article, I hope it will be helpful to everyone's learning.