What should I do if a project does not need to load a huge js plug-in such as jquery to use ajax? I will share with you several ways to use javascript to implement native ajax. Since javascript has various frameworks, such as jquery, ajax has become quite simple. However, for simplicity, you may not need to load a huge js plug-in such as jquery in the project. But what should I do if I want to use ajax? We will share with you several ways to use javascript to implement native ajax.
Before implementing ajax, you must create an XMLHttpRequest object. If you cannot create a browser for this object, you need to create ActiveXObject as follows:
The Code is as follows:
Var xmlHttp;
Function createxmlHttpRequest (){
If (window. ActiveXObject ){
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Else if (window. XMLHttpRequest ){
XmlHttp = new XMLHttpRequest ();
}
(1) Use the xmlHttp created above to implement the simplest ajax get request:
The Code is as follows:
Function doGet (url ){
// Use encodeURI to process parameter values 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:
The Code is as follows:
Function doPost (url, data ){
// Use encodeURI to process parameter values 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 ');
}
}
}