Introduction to Ajax

Posted by dhorn on Sat, 22 Jan 2022 19:14:01 +0100

1,Ajax

Asynchronous JavaScript and XML

ajax is not a new programming language, but a technology for creating better, faster and more interactive web applications.

Increase B/S experience (Browser / server)

In 2005, Google made AJAX popular through its Google suggest. Google Suggest can automatically help you search for words.

Google Suggest uses AJAX to create a highly dynamic web interface: when you enter keywords in Google's search box, JavaScript will send these characters to the server, and then the server will return a list of search suggestions.
Just like the domestic Baidu search box!

Traditional web pages (that is, web pages without ajax Technology) need to reload the whole web page if they want to update the content or submit a form.

Web pages using ajax technology can realize asynchronous local update through a small amount of data exchange in the background server.

With Ajax, users can create a direct, highly available, richer and more dynamic Web user interface close to local desktop applications.

Fake Ajax

We can use a tag on the front end to fake an ajax look. iframe tag

1. Create a new module: sspring mvc-06-ajax and import web support!

2. Write an Ajax - frame HTML use iframe test to feel the effect

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>RYGAR</title>
</head>
<body>
 
<script type="text/javascript">
    window.onload = function(){
        var myDate = new Date();
        document.getElementById('currentTime').innerText = myDate.getTime();
    };
 
    function LoadPage(){
        var targetUrl =  document.getElementById('url').value;
        console.log(targetUrl);
        document.getElementById("iframePosition").src = targetUrl;
    }
 
</script>
 
<div>
    <p>Please enter the address to load:<span id="currentTime"></span></p>
    <p>
        <input id="url" type="text" value="https://www.baidu.com/"/>
        <input type="button" value="Submit" onclick="LoadPage()">
    </p>
</div>
 
<div>
    <h3>Load page location:</h3>
    <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>
 
</body>
</html>

3. Use IDEA to open the browser to test!

With AJAX, you can:

  • When registering, enter the user name to automatically detect whether the user already exists.

  • When logging in, you will be prompted that the user name and password are incorrect

  • When deleting a data row, the row ID is sent to the background, and the background deletes it in the database. After the database is deleted successfully, the data row is also deleted in the page DOM.

  • ... wait

2. XMLHttpRequest object

  • XMLHttpRequest is the foundation of AJAX.
  • All modern browsers support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject).
  • XMLHttpRequest is used to exchange data with the server in the background. This means that a part of a web page can be updated without reloading the whole web page.

2.1. Create XMLHttpRequest object

All modern browsers (IE7 +, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.

Syntax for creating XMLHttpRequest object:

var xhr=new XMLHttpRequest();

2.2. Send a request to the server

The XMLHttpRequest object is used to exchange data with the server. To send the request to the server, we use the open() and send() methods of the XMLHttpRequest object.

methoddescribeparameter
open(method,url,async)Specify the type of request, URL, and whether to process the request asynchronouslyMethod: request method, GET or POST; url: request path; async: true (asynchronous) or false (synchronous)
send(string)Send request to serverstring: request parameter, only used for POST requests. Format: name1 = value1 & Name2 = Value2

GET request

A simple GET request:

xhr.open("GET","DemoAJAXServlet",true);
xhr.send();

POST request

A simple POST request:

xhr.open("POST","DemoAJAXServlet",true);
xhr.send();

If you need POST data like an HTML form, use setRequestHeader() to add an HTTP header. Then fill in the sent data in the send() method:

xhr.open("POST","DemoAJAXServlet",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=tom&age=20");

2.3 server response

Get the response from the server, using the responseText or responseXML attribute of the XMLHttpRequest object.

document.getElementById("myDiv").innerHTML=xhr.responseText;

When the request is sent to the server, some response based tasks need to be performed. The onreadystatechange event is triggered whenever the readyState changes. The readyState property holds the status information of XMLHttpRequest.

Here are three important properties of the XMLHttpRequest object:

attributedescribe
onreadystatechangeState change event trigger, which is called whenever the readyState property changes
readyStateThe status of XMLHttpRequest is stored. Changes from 0 to 4. 0: request not initialized; 1: The server connection has been established; 2: Request received; 3: Request processing; 4: The request has completed and the response is ready
statusResponse status code. 200: successful; 404: page not found

In the onreadystatechange event, when readyState is equal to 4 and the status is 200, the response is ready:

xhr.onreadystatechange=function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        document.getElementById("myDiv").innerHTML=xhr.responseText;
    }
}

2.4 code implementation

//1. Create the ajax core object XMLHttpRequest
var ajax = new XMLHttpRequest();
//2. Establish a connection with the server
ajax.open("post","testAjax");
//3. Set the request header. If the request method is post, the request header must be set
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//4. Register event listening and listen for changes in the state of server-side objects
//Function: after processing, the server responds to the client and receives the response data through this function. Later, this function is called a callback function in ajax
ajax.onreadystatechange = function(){
  //Judge whether the status of the server object is completed
  if(ajax.readyState == 4){ //4 indicates that the server is complete
    //Judge whether the server has processed successfully
    if(ajax.status == 200){ //200 response status code, indicating successful processing
      alert("Data returned in response:" + ajax.responseText);
    }else {
      alert("Processing failed:" + ajax.status);
    }
  }
}
//5. Send request
var name = document.getElementById("name").value;
ajax.send("name="+name);

3. jQuery is learning

Topics: Java Javascript Ajax