Home Web Front-end JS Tutorial An introduction to the functions and uses of Ajax

An introduction to the functions and uses of Ajax

Jan 30, 2024 am 09:30 AM
ajax form submission

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1259
29
C# Tutorial
1233
24
How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to implement front-end and back-end interaction in layui How to implement front-end and back-end interaction in layui Apr 01, 2024 pm 11:33 PM

There are the following methods for front-end and back-end interaction using layui: $.ajax method: Simplify asynchronous HTTP requests. Custom request object: allows sending custom requests. Form control: handles form submission and data validation. Upload control: easily implement file upload.

The difference between event and $event in vue The difference between event and $event in vue May 08, 2024 pm 04:42 PM

In Vue.js, event is a native JavaScript event triggered by the browser, while $event is a Vue-specific abstract event object used in Vue components. It is generally more convenient to use $event because it is formatted and enhanced to support data binding. Use event when you need to access specific functionality of the native event object.

How to build a single-page application using PHP How to build a single-page application using PHP May 04, 2024 pm 06:21 PM

Steps to build a single-page application (SPA) using PHP: Create a PHP file and load Vue.js. Define a Vue instance and create an HTML interface containing text input and output text. Create a JavaScript framework file containing Vue components. Include JavaScript framework files into PHP files.

What is the role of Serverlet in Java What is the role of Serverlet in Java Apr 12, 2024 pm 02:39 PM

Servlet serves as a bridge for client-server communication in Java Web applications and is responsible for: processing client requests; generating HTTP responses; dynamically generating Web content; responding to customer interactions; managing HTTP session state; and providing security protection.

What is the abbreviation of dom in js? What is the abbreviation of dom in js? May 09, 2024 am 12:00 AM

DOM (Document Object Model) is an API for accessing, manipulating and modifying the tree structure of HTML/XML documents. It represents the document as a node hierarchy, including Document, Element, Text and Attribute nodes, which can be used to: access and modify Document structure Access and modify element styles Create/modify HTML content in response to user interaction

See all articles