Home > Web Front-end > JS Tutorial > body text

An introduction to the functions and uses of Ajax

王林
Release: 2024-01-30 09:30:06
Original
522 people have browsed it

An introduction to the functions and uses of Ajax

Overview of the practical functions of Ajax

In modern Web development, Ajax (Asynchronous JavaScript and XML) has become a very commonly used tool. By using Ajax, we can achieve data interaction without refreshing on the page, improve user experience and reduce server load. This article will provide an overview of several practical functions of Ajax, with specific code examples.

1. Submit the form without refreshing

One of the most basic functions of using Ajax is to submit the form without refreshing. Traditional HTML form submission causes the entire page to refresh, but using Ajax allows you to submit the form and receive the server's response without refreshing the page.

The following is a simple implementation example:

<form id="myForm" action="submit.php" method="post">
  <input type="text" name="username">
  <input type="password" name="password">
  <button onclick="submitForm()">提交</button>
</form>

<script>
function submitForm() {
  var form = document.getElementById("myForm");
  var formData = new FormData(form);

  var xhr = new XMLHttpRequest();
  xhr.open("POST", form.action, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      var response = xhr.responseText;
      // 处理服务器响应
    }
  };
  xhr.send(formData);
}
</script>
Copy after login

In the above code, when the submit button is clicked, the submitForm() function will be called. This function obtains the form data through the FormData object, and uses the XMLHttpRequest object to send a POST request to the server. When the server returns a response, we can handle the server's response in the xhr.onreadystatechange event.

2. Dynamically load data

Through Ajax, we can dynamically load data without refreshing the entire page. This is useful when creating highly interactive web applications.

The following code shows how to use Ajax to dynamically load data from the server side and display it on the page:

<div id="dataContainer"></div>

<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    var data = JSON.parse(xhr.responseText);

    var container = document.getElementById("dataContainer");
    data.forEach(function(item) {
      var element = document.createElement("div");
      element.textContent = item.name;
      container.appendChild(element);
    });
  }
};
xhr.send();
</script>
Copy after login

In the above code, we use the XMLHttpRequest object to send GET Request to the server and obtain data named data.json. When the server returns a response, we use JSON.parse() to parse the text of the response and display the data in a <div> element named dataContainer middle.

3. Real-time search

Ajax can also be used to implement real-time search function. When the user enters a keyword in the search box, the page will immediately send a request to the server and load the corresponding search results, thereby achieving the effect of displaying the search results in real time.

The following is a basic real-time search sample code:

<input type="text" id="searchInput" oninput="search()" placeholder="搜索...">

<ul id="searchResults"></ul>

<script>
function search() {
  var keyword = document.getElementById("searchInput").value;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "search.php?keyword=" + keyword, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      var results = JSON.parse(xhr.responseText);

      var resultsList = document.getElementById("searchResults");
      resultsList.innerHTML = "";

      results.forEach(function(item) {
        var li = document.createElement("li");
        li.textContent = item.name;
        resultsList.appendChild(li);
      });
    }
  };
  xhr.send();
}
</script>
Copy after login

In the above code, when the user enters keywords in the search box, the search() function will be called. This function searches by getting the value of the input box and sending it to the server as a parameter. When the server returns search results, we display the results in a <ul></ul> element named searchResults.

Conclusion

This article introduces three common functions of Ajax: submitting forms without refreshing, dynamically loading data and real-time search. Through practical code examples, we show how to use Ajax to implement these functions on the page. Of course, this is just the tip of the iceberg of Ajax functionality. Ajax has many other powerful features and uses. I hope this article can provide you with some inspiration on the use of Ajax and play a role in your web development projects.

The above is the detailed content of An introduction to the functions and uses of Ajax. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!