Introduction to Ajax

Ajax: "Asynchronous Javascript And XML,",

It's not new technology, it's just the integration of the original technology.

1. Use CSS and XHTML to represent.
2. Use DOM model for interaction and dynamic display.
3. Use XMLHttpRequest to communicate with the server asynchronously.
4. Use javascript to bind and call. It's not new technology, it's just the integration of the original technology.

Effect:

If we want to refresh the local content of our web page. Then you need to reload the entire page. The user experience is not very good. To solve the problem of local refresh. Keep the rest still and refresh only some places.

As we said before, Ajax is not a new technology. It's all about wrapping up existing technologies and using them to do the work.  

Now let's give you an example, or take our judgment of whether the user name has been registered as an example.  

Traditional way:

1. Enter the user name,
2. Click a button to verify.
3. Submit the data to the server
4. The server helps us complete the verification in the background and feeds back information.
5. We will prompt the user on the browser and give the result

Ajax mode:

The ajax way is the same as the previous way in terms of things to be done. AJAX is not good either. You don't need to visit the server to know if your user name is occupied. So how does it work?

1. Get the text content of our input box document.getElementById("username").value through JS

2. Execute the request through XmlHttpRequest. XmlHttpRequest is actually a combination of XML + http + Request.

3. After the request is completed, receive the result, and then use js to complete the prompt.  

4. You can use css style to increase the prompt effect.

 

Let's talk about asynchronous synchronization first: (here's a brief description. There are a lot of detailed descriptions on the Internet, baidu ha that needs to be explained in detail)

Synchronization: after sending a request, wait until the server responds, and then send the second request

Asynchronous: after sending a request, do not wait for the result, and then send the second request

Get request:

1. Create XmlHttpRequest object. This part of the code for creating objects needs to be judged according to different browsers, and there is no prompt, so you can write it yourself. Copy directly later.  

<script type="text/javascript">
function ajaxFunction(){
           var xmlHttp;
           try{ // Firefox, Opera 8.0+, Safari
                    xmlHttp=new XMLHttpRequest();
            }catch (e){
               try{// Internet Explorer
                         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
              }catch (e){
                  try{
                         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (e){}
              }
        }
        return xmlHttp;
}
</script>

2. Send the request directly without data.       

<script type="text/javascript">  
    function get(){
        //No data, direct request.
        //Get xmlhttprequest object
        var request = ajaxFunction();
        // Parameter 1: execute get request, parameter 2: request address, parameter 3: asynchronous request or not.
        request.open("GET", "Demo01", true);
        //Send the request.
        request.send();
       }
</script>

------------------------------ data on the following

<script type="text/javascript">   
    function get(){
        //Get xmlhttprequest object
        var request = ajaxFunction();
        // Parameter 1: execute get request, parameter 2: request address, parameter 3: asynchronous request or not.
        request.open("GET", "Demo01?name=zhangsan&age=18", true);
        request.send();
    }
</script>

Post request:

Post request and get request are basically similar. The difference lies in the different data transmission methods. Get is spliced directly behind the address. But the post method transfers the past through the send method. And set a request header.
Basically, if you understand the Http protocol, it's not so difficult to understand the Post request code.

1. Create XmlHttpRequest object. This part of the code for creating objects needs to be judged according to different browsers, and there is no prompt, so you can write it yourself. Copy directly later.  

<script type="text/javascript">  
function ajaxFunction(){
           var xmlHttp;
           try{ // Firefox, Opera 8.0+, Safari
                    xmlHttp=new XMLHttpRequest();
            }catch (e){
               try{// Internet Explorer
                         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
              }catch (e){
                  try{
                         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (e){}
              }
        }
        return xmlHttp;
}
</script>

2. Send the request directly without data.         

<script type="text/javascript">       
    function post(){
         //No data, direct request.
        //Get xmlhttprequest object
        var request = ajaxFunction();
        // Parameter 1: execute get request, parameter 2: request address, parameter 3: asynchronous request or not.
        request.open("POST", "Demo01", true);
        //Send the request.
        request.send();
    }
</script>

------------------------------ data on the following

<script type="text/javascript">       
    function post(){ 
        //Get xmlhttprequest object
        var request = ajaxFunction();
        // Parameter 1: execute get request, parameter 2: request address, parameter 3: asynchronous request or not.
        request.open("POST", "Demo01", true);
        //Setting the request header means that the data transferred is a url encoded form data
        request.setHeader("Content-Type" , "application/x-www-form-urlencoded");    
        request.send("name=zhangsan&age=18");
    }  
</sctipt>

Get server's response: get and Post are the same

After two kinds of requests for data submission, Get and Post, are basically used, we should think about the problem of obtaining data. We have been selflessly submitting data to the server, so how can we Get the data returned by the server through Ajax?
Here we rely on the event onreadystatechange of xmlhttprequest, which is used to monitor the status of our request, such as success or failure. If successful, you need to rely on the responseText or responseXML attribute of xmlhttprequest to get the data

Complete example:

<script type="text/javascript">    
         ..................
function DeDaorespone(){    //Get response
        //The code to get the xmlhttprequest object is the same as before, which will not be repeated here.
        var request = ajaxFunction();
        // Parameter 1: execute get request, parameter 2: request address, parameter 3: asynchronous request or not.
        request.open("GET", "Demo01", true);        
   
         //Monitor the status of the request.
        request.onreadystatechange = function(){
            if(request.readyState == 4 && request.status == 200 ){
                //Set the label with node id myDiv to the response text we requested
                document.getElementById("myDiv").innerHTML=request.responseText;
            }
        }
        //Send the request.
        request.send();
    }
</script>

Case study:

Ajax Get:   

<script type="text/javascript">    
         .................. 
var request = ajaxFunction();
    var name = document.getElementById("name").value;
    request.onreadystatechange=function(){
         if (request.readyState==4 && request.status==200){
             var result = request.responseText;
             if(result == 1){
                 document.getElementById("span1").innerHTML="<font color='red'>User name is already in use</font>";
             }else{
                 document.getElementById("span1").innerHTML="<font color='green'>User name can be used</font>";
             }            
         }
    }
    request.open("GET", "RegisterServlet?name="+name, true);
    request.send();
    //String comparison:
     if(result == '1'){
                 document.getElementById("span1").innerHTML="<font color='red'>User name is already in use</font>";
             }else{
                 document.getElementById("span1").innerHTML="<font color='green'>User name can be used</font>";
             }
</script>

Ajax    Post:

<script type="text/javascript">    
         ..................  
function checkName02(){   
    var request = ajaxFunction();
    var name = document.getElementById("name").value;
    request.onreadystatechange=function(){
        if (request.readyState==4 && request.status==200){
            var result = request.responseText;
            if(result == '1'){
                document.getElementById("span1").innerHTML="<font color='red'>User name occupied 22</font>";
            }else{
                document.getElementById("span1").innerHTML="<font color='green'>User name can use 22</font>";
            }           
        }
    }
    request.open("POST", "RegisterServlet", true);
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    request.send("name="+name);
}
</script>


 

 

Published 10 original articles, won praise 4, visited 100
Private letter follow

Tags: Javascript xml Firefox REST

Posted on Tue, 17 Mar 2020 07:00:21 -0400 by wit77