Home > Web Front-end > JS Tutorial > How to use Ajax? Ajax operation steps

How to use Ajax? Ajax operation steps

青灯夜游
Release: 2018-11-08 14:46:26
Original
2783 people have browsed it

How to use Ajax? This article will introduce Ajax operations to you and let you understand the steps of Ajax operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, let’s summarize the steps of Ajax operation, and then introduce in detail how each step is performed.

1. Call client events

2. Create XMLHttpRequest object

3. Configure XMLHttpRequest object.

4. The XMLHttpRequest object issues an asynchronous request to the Web server.

5. The Web server returns results containing XML documents.

6. The XMLHttpRequest object calls the callback() function and processes the result.

7. Update HTML DOM.

Let’s implement these steps step by step to implement Ajax operations.

Calling client events

JavaScript functions are called as a result of the event.

Example:

<input type =“text”size =“20”id =“userid”name =“id”onkeyup =“validateUserId();”>
Copy after login

Description:

The JavaScript function validateUserId() is mapped as an event handler to the onkeyup event on the input form field, with its id set to "userid".

Create XMLHttpRequest object

var ajaxRequest;  // 使Ajax成为可能的变量!
function ajaxFunction() {
   try {
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
   } catch (e) {
   
      // Internet Explorer浏览器
      try {
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      
         try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
      
            alert("Your browser broke!");
            return false;
         }
      }
   }}
Copy after login

Configure XMLHttpRequest object

In this step, we will write a function that will be triggered by client events and will register a callback function processRequest().

function validateUserId() {
   ajaxFunction();
   
   // 这里的processRequest()是回调函数。
   ajaxRequest.onreadystatechange = processRequest;
   
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
}
Copy after login

Making asynchronous requests to the web server

The source code can be found in the code above. The code written in bold font is responsible for making requests to the web server. This is all done using the XMLHttpRequest object ajaxRequest.

function validateUserId() {
   ajaxFunction();
   
   // 这里的processRequest()是回调函数。
   ajaxRequest.onreadystatechange = processRequest;
   
   if (!target) target = document.getElementById("userid");
   var url = "validate?id = " + escape(target.value);
   
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
}
Copy after login

Assuming "Zara" is entered in the user ID box, then in the above request, the URL will be set to "validate?id = Zara".

Webserver returns results containing XML documents

Server-side scripting can be implemented in any language, but its logic should be as follows.

1. Get the request from the client.

2. Parse the input from the client.

3. Need to be processed.

4. Send the output to the client.

If we assume you want to write a servlet, then this is a piece of code.

public void doGet(HttpServletRequest request,
   HttpServletResponse response) throws IOException, ServletException {
   String targetId = request.getParameter("id");
   
   if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("<valid>true</valid>");
   } else {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("<valid>false</valid>");
   }
}
Copy after login

Callback function calls processRequest()

The XMLHttpRequest object is configured to call the processRequest() function when the readyState state of the XMLHttpRequest object changes. Now this function will receive the results from the server and will perform the required processing. As shown in the following example, it sets the variable message to true or false based on the return value of the Webserver.

function processRequest() {
   if (req.readyState == 4) {
      if (req.status == 200) {
         var message = ...;
...
}
Copy after login

Update HTML DOM

This is the last step, in this step, the HTML page will be updated. It happens in the following way:

1. JavaScript uses the DOM API to obtain a reference to any element in the page.

2. The recommended way to get elements to reference is to call.

document.getElementById("userIdMessage"),
Copy after login

3. You can now use JavaScript to modify the attributes of elements, modify the style attributes of elements, or add, delete or modify child elements.

Give an example:

js code:

   <!--
   function setMessageUsingDOM(message) {
      var userMessageElement = document.getElementById("userIdMessage");
      var messageText;
      
      if (message == "false") {
         userMessageElement.style.color = "red";
         messageText = "Invalid User Id";
      } else {
         userMessageElement.style.color = "green";
         messageText = "Valid User Id";
      }
      
      var messageBody = document.createTextNode(messageText);
      
      // 如果消息体元素已简单创建
      // 需要替换它,否则追加新元素
      if (userMessageElement.childNodes[0]) {
         userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
      } else {
         userMessageElement.appendChild(messageBody);
      }
   }
   -->
Copy after login

html code:

<div id = "userIdMessage"><div>
Copy after login

If you have understood the seven steps mentioned above , then you have almost completed the Ajax operation. You can try it yourself to deepen your understanding. I hope it will be helpful to your study. Recommended related video tutorials: Ajax Tutorial, JavaScript Tutorial!

The above is the detailed content of How to use Ajax? Ajax operation steps. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template