📜  ajax exmaple\ - Javascript (1)

📅  最后修改于: 2023-12-03 15:13:17.565000             🧑  作者: Mango

AJAX Example - JavaScript

AJAX (Asynchronous JavaScript and XML) is a technique used in web development to update a web page without reloading the page. This can improve the user experience by making the site feel faster and more responsive. AJAX allows a web page to exchange data with a web server in the background, without interrupting the user's experience.

This article will provide an AJAX example in JavaScript. Specifically, we will make a GET request to a web server to retrieve data and display it on the web page.

Prerequisites

You will need a basic understanding of HTML, CSS, and JavaScript to follow along with this example. You will also need a web server that can serve the data we will be requesting in our AJAX call.

Making the AJAX Request

To make an AJAX request in JavaScript, we will use the XMLHttpRequest object. This object allows us to send an HTTP request to a web server and handle the server's response.

Here is an example of making a GET request using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    const data = JSON.parse(this.responseText);
    // Do something with the data
  }
};
xhr.open('GET', '/data', true);
xhr.send();

Let's break down this example:

  • We create a new XMLHttpRequest object using the new operator.
  • We set the onreadystatechange property of the object to a function that will handle the server's response. This function will be called multiple times as the request progresses, and we will check for a ready state of 4 (request is finished) and a status of 200 (request was successful).
  • We open the request using the open method, which takes three arguments: the HTTP method (GET), the URL of the resource we are requesting (/data), and a boolean flag indicating whether the request should be asynchronous (true).
  • We send the request using the send method.

Note that in this example, we are assuming that the server will return data in JSON format. If the server returns data in a different format, we will need to adjust our code accordingly.

Displaying the Data

Once we have retrieved the data from the server, we can display it on the web page. Here is an example of displaying the data in a table:

<!DOCTYPE html>
<html>
<head>
  <title>AJAX Example</title>
</head>
<body>
  <table id="data-table"></table>
  <script>
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        const data = JSON.parse(this.responseText);
        const table = document.getElementById('data-table');
        // Add table headers
        const headersRow = document.createElement('tr');
        Object.keys(data[0]).forEach(key => {
          const th = document.createElement('th');
          th.textContent = key;
          headersRow.appendChild(th);
        });
        table.appendChild(headersRow);
        // Add table rows
        data.forEach(rowData => {
          const row = document.createElement('tr');
          Object.values(rowData).forEach(value => {
            const td = document.createElement('td');
            td.textContent = value;
            row.appendChild(td);
          });
          table.appendChild(row);
        });
      }
    };
    xhr.open('GET', '/data', true);
    xhr.send();
  </script>
</body>
</html>

Let's break down this example:

  • We create an HTML table with an empty id attribute to allow us to select it later using JavaScript.
  • We create a new XMLHttpRequest object and set the onreadystatechange property to a function that will handle the server's response, just like we did in the previous example.
  • We create a headersRow element to hold the table headers, and use the Object.keys method to iterate over the keys of the first element in the data array (we assume here that all elements have the same keys). For each key, we create a th element and set its text content to the key value. We then add the th element to the headersRow element. Finally, we add the headersRow element to the table.
  • We iterate over each element in the data array using the forEach method. For each element, we create a new row element and use the Object.values method to iterate over the values of the element. For each value, we create a td element and set its text content to the value. We then add the td element to the row element. Finally, we add the row element to the table.
Conclusion

In this article, we provided an AJAX example in JavaScript. Specifically, we showed how to make a GET request to a web server to retrieve data and display it on the web page. This technique can be useful in scenarios where we need to update a web page without reloading the page, improving the user experience.