Since javascript has various frameworks, such as jquery, using 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:
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe 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 ');
}
}
}