function getXmlDoc() {var xmlDoc;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, SafarixmlDoc = new XMLHttpRequest();}else {// code for IE6, IE5xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");}
return xmlDoc;}
function get(url) {// Return a new promise.return new Promise(function(resolve, reject) {// Do the usual XHR stuffvar req = new XMLHttpRequest();req.open('GET', url);
req.onload = function() {// This is called even on 404 etc// so check the statusif (req.status == 200) {// Resolve the promise with the response textresolve(req.response);}else {// Otherwise reject with the status text// which will hopefully be a meaningful errorreject(Error(req.statusText));}};
// Handle network errorsreq.onerror = function() {reject(Error("Network Error"));};
// Make the requestreq.send();});}
function microAjax(B,A){this.bindFunction=function(E,D){return function(){return E.apply(D,[D])}};this.stateChange=function(D){if(this.request.readyState==4){this.callbackFunction(this.request.responseText)}};this.getRequest=function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP")}else{if(window.XMLHttpRequest){return new XMLHttpRequest()}}return false};this.postBody=(arguments[2]||"");this.callbackFunction=A;this.url=B;this.request=this.getRequest();if(this.request){var C=this.request;C.onreadystatechange=this.bindFunction(this.stateChange,this);if(this.postBody!==""){C.open("POST",B,true);C.setRequestHeader("X-Requested-With","XMLHttpRequest");C.setRequestHeader("Content-type","application/x-www-form-urlencoded");C.setRequestHeader("Connection","close")}else{C.open("GET",B,true)}C.send(this.postBody)}};
function createXmlHttpRequestObject() {// will store the reference to the XMLHttpRequest objectvar xmlHttp;// if running Internet Explorerif (window.ActiveXObject) {try {xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {xmlHttp = false;}}// if running Mozilla or other browserselse {try {xmlHttp = new XMLHttpRequest();} catch (e) {xmlHttp = false;}}// return the created object or display an error messageif (!xmlHttp)alert("Error creating the XMLHttpRequest object.");elsereturn xmlHttp;}
Step 3.使用XMLHttpRequest对象发出异步HTTP请求
function process() {// proceed only if the xmlHttp object isn't busyif (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {// retrieve the name typed by the user on the formitem = encodeURIComponent(document.getElementById("input_item").value);// execute the your_file.php page from the serverxmlHttp.open("GET", "your_file.php?item=" + item, true);// define the method to handle server responsesxmlHttp.onreadystatechange = handleServerResponse;// make the server requestxmlHttp.send(null);}}
Step 4.当收到来自服务器的消息时自动执行
function handleServerResponse() {
// move forward only if the transaction has completedif (xmlHttp.readyState == 4) {// status of 200 indicates the transaction completed successfullyif (xmlHttp.status == 200) {// extract the XML retrieved from the serverxmlResponse = xmlHttp.responseText;document.getElementById("put_response").innerHTML = xmlResponse;// restart sequence}// a HTTP status different than 200 signals an errorelse {alert("There was a problem accessing the server: " + xmlHttp.statusText);}}}
const xhr = new XMLHttpRequest();xhr.open('GET', 'https://example.com/data.json'); // by default asyncxhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {if(this.status == 200) {// onload called even on 404 etc so check the statusconsole.log(this.response); // No need for JSON.parse()}};
xhr.onerror = function() {// error};
xhr.send();
var my_ajax_call=ajaxCall({url: url,type: method,data: {data:value},dataType: 'json',async:false,//synchronous request. Default value is truetimeout:10000,//default timeout 20000progress:function(loadTime,status){console.log(loadTime);},success: function (result, status) {console.log(result);},error :function(result,status){console.log(result);}});
var request = new XMLHttpRequest();request.open('POST', '/my/url', true);request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');request.send(JSON.stringify(data));
httpRequest.onreadystatechange = function(){// Process the server response here.if (httpRequest.readyState === XMLHttpRequest.DONE) {if (httpRequest.status === 200) {alert(httpRequest.responseText);} else {alert('There was a problem with the request.');}}}
/*create an XMLHttpRequest object*/
let GethttpRequest=function(){let httpRequest=false;if(window.XMLHttpRequest){httpRequest =new XMLHttpRequest();if(httpRequest.overrideMimeType){httpRequest.overrideMimeType('text/xml');}}else if(window.ActiveXObject){try{httpRequest =new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{httpRequest =new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}}if(!httpRequest){return 0;}return httpRequest;}
/*Defining a function to make the request every time when it is needed*/
function MakeRequest(){
let uriPost ="myURL";let xhrPost =GethttpRequest();let fdPost =new FormData();let date =new Date();
/*data to be sent on server*/let data = {"name" :"name","lName" :"lName","phone" :"phone","key" :"key","password" :"date"};
let JSONdata =JSON.stringify(data);fdPost.append("data",JSONdata);xhrPost.open("POST" ,uriPost, true);xhrPost.timeout = 9000;/*the time you need to quit the request if it is not completed*/xhrPost.onloadstart = function (){/*do something*/};xhrPost.onload = function (){/*do something*/};xhrPost.onloadend = function (){/*do something*/}xhrPost.onprogress =function(){/*do something*/}
xhrPost.onreadystatechange =function(){
if(xhrPost.readyState < 4){
}else if(xhrPost.readyState === 4){
if(xhrPost.status === 200){
/*request succesfull*/
}else if(xhrPost.status !==200){
/*request failled*/
}
}
}xhrPost.ontimeout = function (e){/*you can stop the request*/}xhrPost.onerror = function (){/*you can try again the request*/};xhrPost.onabort = function (){/*you can try again the request*/};xhrPost.overrideMimeType("text/plain; charset=x-user-defined-binary");xhrPost.setRequestHeader("Content-disposition", "form-data");xhrPost.setRequestHeader("X-Requested-With","xmlhttprequest");xhrPost.send(fdPost);}
/*PHP side<?php//check if the variable $_POST["data"] exists isset() && !empty()$data =$_POST["data"];$decodedData =json_decode($_POST["data"]);//show a single item from the formecho $decodedData->name;
?>*/
/*Usage*/MakeRequest();