To complete the AJAX request using native JavaScript, you should first create an object XMLHttpRequest, taking into account the low version of IE browser, using the ActiveXObject object, the code into the following:
varrequest;if(Windoe. Xmlhtprequest) {Request=NewXMLHttpRequest ();}Else{Request=NewActiveXObject ();}functionSuccess (text) {vartextarea = document.getElementById (' Test-ie-response-text ')); Textarea.value=text;}functionfail (code) {vartextarea = document.getElementById (' Test-ie-response-text ')); Textarea.value= ' Error code: ' +Code;}varRequest =NewActiveXObject (' microsoft.xmlhttp ');//New Microsoft.XMLHTTP ObjectRequest.onreadystatechange=function() {//function is callback when state changes if(Request.readystate = = 4) {//successfully completed //To determine the response result: if(Request.status = = 200) { //successful, get the text of the response via ResponseText: returnsuccess (Request.responsetext); } Else { //failure, according to the response code to determine the reason for failure: returnfail (request.status); } } Else { //the HTTP request is still continuing ... }}//Send request:Request.open (' GET ', '/api/categories '); Request.send (); Alert (' Request sent, please wait for response ... ');
Native JavaScript completes AJAX requests