Home >Web Front-end >Front-end Q&A >How to use AJAX in JavaScript and keep the page from refreshing

How to use AJAX in JavaScript and keep the page from refreshing

PHPz
PHPzOriginal
2023-04-21 09:12:21978browse

As websites become more and more complex and require a higher user experience, AJAX (Asynchronous JavaScript and XML) technology has become one of the essential skills for website front-end development. It allows you to send requests to the server via JavaScript without making the entire page reload. This makes the website faster and smoother, and users don't feel any interruption. This article will explain how to use AJAX in JavaScript and keep the page from refreshing.

  1. AJAX and XMLHttpRequest

Using AJAX in Javascript requires the use of the XMLHttpRequest object because it is the core of performing asynchronous requests. The XMLHttpRequest object is a built-in JavaScript object, often referred to as XHR for short. It provides an API for asynchronous requests through the HTTP protocol, allowing us to obtain server responses, process requests and update web pages without refreshing the entire page.

The following is a simple example of using XHR to make a request:

let request = new XMLHttpRequest();
request.open('GET', '/api/data', true);
request.onreadystatechange = function() {
   if(request.readyState === 4 && request.status === 200) {
      let response = JSON.parse(request.responseText);
      // 处理响应并更新页面
   }
};
request.send();

In the above code, we create an XMLHttpRequest object instance and open a GET request using the open() method . After opening the GET request, we set a handler function for the onreadystatechange event, which will be called when the readyState attribute of the XHR object changes, and check whether the status code of the server response is 200. If all goes well, we parse the response text (usually in JSON format) and update the relevant data on the page.

  1. AJAX in jQuery

If you use jQuery, it abstracts a more simplified API under the hood to use AJAX. Here is a complete jQuery AJAX example:

$.ajax({
   url: '/api/data',
   type: 'GET',
   dataType: 'json',
   success: function(data) {
      // 成功后更新页面
   }
});

In the above code, we send a GET request using jQuery's $.ajax() method and execute a handler function on success. Similar to using the XMLHttpRequest object, we can update the page content in the success function.

  1. Updating page content using AJAX

Once your AJAX request successfully returns a response, you may want to use JavaScript to update the content on the page to reflect the new data. The following is a simple example:

function updatePage(response) {
   let div = document.getElementById('data-display');
   let html = '';
   response.forEach(function(item) {
      html += '<div>' + item.name + '</div>';
   });
   div.innerHTML = html;
}

In the above code, we define an updatePage() function to update the page content. It first finds the div element with the ID "data-display" and internally builds an HTML string, then sets that string to that element's innerHTML.

  1. Avoid duplicate requests

Since AJAX is executed asynchronously, users may continuously initiate multiple identical or different requests, which will cause these requests to be heavily interleaved. This can lead to concurrency issues and excessive server load. Therefore, when sending AJAX requests, we should pay attention to avoid duplicate requests.

One way to avoid duplicate requests is to use a tag (or flag) variable to check whether the previous request has completed. For example:

let requesting = false;
function makeRequest() {
   if(requesting) {
      return;
   }
   requesting = true;
   $.ajax({
      url: '/api/data',
      type: 'GET',
      dataType: 'json',
      success: function(data) {
         updatePage(data);
      },
      complete: function() {
         requesting = false;
      }
   });
}

In the above code, we use the variable "requesting" to identify whether a request has been issued. To avoid multiple requests, we first check the status of this variable before starting to send the request. If the variable is true, it returns and no new requests are sent. If the request succeeds or fails, we reset the variable to false in the complete callback function to allow new requests.

  1. Use AJAX to implement dynamic forms

One of the most common scenarios for AJAX is to submit data through dynamic forms and get the server response without refreshing the entire page. The following is an example of using jQuery to implement a dynamic form:

<form id="my-form">
   <input type="text" id="name" name="name" placeholder="Your name">
   <button type="submit">Submit</button>
</form>
<div id="result"></div>

<script type="text/javascript">
   $("#my-form").submit(function(e) {
      e.preventDefault();
      let $form = $(this);
      let url = $form.attr('action');
      let formData = $form.serialize();
      $.ajax({
         type: "POST",
         url: url,
         data: formData,
         dataType: 'json',
         success: function(response) {
            $('#result').html("Thank you, " + response.name + "!");
         }
      });
   });
</script>

In the above code, we define a form and bind a submit event to it. When the user submits the form, we use the serialize() method to collect the form data and send it to the server as data for the AJAX request. If the server successfully processes and returns the JSON response, we update a div element with the ID "result" on the page with the data in the response.

Conclusion

As you can see, AJAX makes it easier and more comfortable to send and receive data to the server. This article explains how to use AJAX in Javascript to send asynchronous requests and update content without refreshing the entire page. Finally we discussed how to avoid duplicate requests and implement dynamic form submission. AJAX is a very useful technology that can make your website faster and smoother, and will greatly improve the user experience.

The above is the detailed content of How to use AJAX in JavaScript and keep the page from refreshing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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