Explanation and Use of XMLHttpRequest Objects in Ajax

Keywords: Javascript Firefox Attribute Java

Ajax technology can complete partial page refresh and realize asynchronous data transmission between browser and server. The XMLHttpRequest object in JavaScript is the core object of Ajax technology, which provides the ability to send requests asynchronously.

1. Examples of XMLHttpRequest object acquisition:

function getXMLHttpRequest(){
    var xmlhttp;
        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;
}

The XMLHttpRequest object can be accessed in different ways depending on the browser.

The attributes of the XMLHttpRequest object are introduced.
1>. attribute
1)readyState :
0: The request is not initialized (before calling open()
1: The request was submitted (before sending () was called)
2: The request has been sent (where you can usually get the content header from the response)
3: Request processing (part of the data is usually available in the response, but the server has not completed the response)
4: The request has been completed (the server response can be accessed and used)

2) responseText: Retrieve the data returned by the server
3) ResponsseXML: Retrieve the data returned by the server
4) Status: Return the server status code such as 404, 200, etc.

2>. method
1) open(method,url, asynch): Connect to the server
Where method represents HTTP invocation method, GET and POST are commonly used.
url represents the address of the invoked server
asynch means asynchronism, true means asynchronism, and generally this parameter is not written.

Sample code
xmlHttp.open("POST", "url");
xmlHttp.open("GET", "url?name=xxx&pwd=xxx");

2) send (content): send a request
GET submission
Data in the URL: xmlHttp.send(null);
POST submission:
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");

xmlHttp.send("name=xxx&pwd=xxx");

setRequestHeader(): Set the request header information

3. Event Processor
onreadystatechange: a function that handles server responses;

Example: A simple username check:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">

function getXMLHttpRequest(){
    var xmlhttp;
        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;
}

 function checkName(){
    //Get the username 
       var name=document.getElementsByTagName("input")[0];
       //Create XMLHttpRequest
       var xhr=getXMLHttpRequest();
     //Processing result
        xhr.onreadystatechange = function(){
            if(xhr.readyState==4){//Ask for everything to be normal
                if(xhr.status==200){//The server responds well
                    var msg = document.getElementById("msg");
                    //alert(xhr.responseText);
                    if(xhr.responseText=="true"){
                        msg.innerHTML =  "<font color='red'>User name already exists</font>";
                    }else{
                        msg.innerHTML = "have access to";
                    }
                }
            }
        }

       //Create connection
       xhr.open("get","${pageContext.request.contextPath}/checkUsername?name="+name.value);
       //Send request
       xhr.send(null);
 }

 </script>
<title>Insert title here</title>
</head>
<body>
    //User name:<input type="text" name="userName" onblur="checkName()"><span  id="msg"></span></br>
   //Password: <input type="password" name="psw"></br>
</body>
</html>

Posted by myharshdesigner on Sun, 07 Apr 2019 15:54:30 -0700