Since JavaScript has various frameworks, such as jquery, using ajax has become quite simple. But sometimes in order to pursue simplicity, there may be no need to load a huge js plug-in like jquery in the project. But what should I do if I want to use ajax function? Let me share with you several ways to use javascript to implement native ajax.
You must create an XMLHttpRequest object before implementing ajax. If the browser that created the object does not support it, you need to create an ActiveXObject. The specific method is as follows:
var xmlHttp;
function createxmlHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if ( window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
}
(1) The following uses the xmlHttp created above to implement the simplest ajax get request:
function doGet(url){
// Pay attention to the parameter value passed in It is best to use encodeURI to handle it to prevent garbled characters
createxmlHttpRequest();
xmlHttp.open("GET",url);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
alert('success');
} else {
alert(' fail');
}
}
}
(2) Use the xmlHttp created above to implement the simplest ajax post request:
function doPost(url,data){
// Be careful when passing parameter values. It is best to use encodeURI to handle it to prevent garbled characters
createxmlHttpRequest();
xmlHttp.open("POST",url);
xmlHttp.setRequestHeader("Content-Type","application/x-www -form-urlencoded");
xmlHttp.send(data);
xmlHttp.onreadystatechange = function() {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200) ) {
alert('success');
} else {
alert('fail');
}
}
}