Native JS Ajax GET and POST request instance code

  • 2021-06-28 08:27:16
  • OfStack

The GET request code for ajax of javascript/js is as follows:


<script type="text/javascript"> 
/*  Establish  XMLHttpRequest  object  */ 
var xmlHttp; 
function GetXmlHttpObject(){ 
 * if (window.XMLHttpRequest){ 
 * // code for IE7+, Firefox, Chrome, Opera, Safari 
 * xmlhttp=new XMLHttpRequest(); 
 * }else{// code for IE6, IE5 
 * xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
 * } 
 * return xmlhttp; 
} 
// -----------ajax Method -----------// 
function getLabelsGet(){ 
 * xmlHttp=GetXmlHttpObject(); 
 * if (xmlHttp==null){ 
 * alert(' Your browser does not support it AJAX ! '); 
 * return; 
 * } 
 * var id = document.getElementById('id').value; 
 * var url="http://www.Leefrom.com?id="+id+"&t/"+Math.random(); 
 * xmlHttp.open("GET",url,true); 
 * xmlHttp.onreadystatechange=favorOK;// After sending the event, you receive information to call the function  
 * xmlHttp.send(); 
}
function getOkGet(){ 
 * if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){ 
 * //  Local Tip: Loading  
 * } 
 * if (xmlHttp.readyState==4 && xmlHttp.status==200){ 
 * var d= xmlHttp.responseText; 
 * //  Processing Return Results  
 * } 
} 
</script>

POST request from ajax of javascript/js:


<script type="text/javascript"> 
/*  Establish  XMLHttpRequest  object  */ 
var xmlHttp; 
function GetXmlHttpObject(){ 
if (window.XMLHttpRequest){ 
// code for IE7+, Firefox, Chrome, Opera, Safari 
xmlhttp=new XMLHttpRequest(); 
}else{// code for IE6, IE5 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
return xmlhttp; 
} 
// -----------ajax Method -----------// 
function getLabelsPost(){ 
xmlHttp=GetXmlHttpObject(); 
if (xmlHttp==null){ 
alert(' Your browser does not support it AJAX ! '); 
return; 
} 
var url="http://www.lifefrom.com/t/"+Math.random(); 
xmlhttp.open("POST",url,true); 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send(); 
xmlHttp.onreadystatechange=getLabelsOK;// After sending the event, you receive information to call the function  
} 
function getOkPost(){ 
if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){ 
//  Local Tip: Loading / Processing  
} 
if (xmlHttp.readyState==4 && xmlHttp.status==200){ 
var d=xmlHttp.responseText; //  Return value  
//  Processing return values  
} 
} 
</script> 

Note: XMLHttpRequest is the basis of AJAX. When creating an XMLHttpRequest object, it must be the same as the ajax method you wrote. < script > < /script > 'In the label!Otherwise, the ajax request will fail and the data cannot be returned.POST/GET request from ajax of javascript/js.


Related articles: