search
HomeWeb Front-endJS TutorialRevealing the power of Ajax
Revealing the power of AjaxJan 30, 2024 am 10:02 AM
real-time interactionform submissionFront-end data updateAsynchronous data interaction

Revealing the power of Ajax

The function of Ajax is revealed, specific code examples are needed

Ajax (Asynchronous JavaScript and XML) is a technology used for asynchronous data interaction on web pages. It allows you to interact with the server, get data and update certain parts of the web page without refreshing the entire page. The emergence of Ajax plays a crucial role in improving user experience, increasing the dynamics and response speed of web pages. This article will reveal the functions of Ajax and provide specific code examples to help readers better understand and use it.

First, let us look at the basic use of Ajax. In HTML pages, asynchronous requests can be sent through JavaScript's XMLHttpRequest object. The following is a simple code example:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

The above code first creates an XMLHttpRequest object, and then sets a callback function onreadystatechange, which will be called when the server returns a response. When readyState is 4 (indicating that the server response has been completed) and status is 200 (indicating success), the code will display the data returned by the server in the id demo element.

Next, we will see an important feature of Ajax - dynamic loading of content. Through Ajax, we can load the content of other pages from the server without refreshing the entire page. The following is an example of using Ajax to dynamically load content:

function loadContent() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("content").innerHTML = this.responseText;
    }
  };
  var pageUrl = "news.html";
  xhttp.open("GET", pageUrl, true);
  xhttp.send();
}

In the above code, a GET request is sent through the XMLHttpRequest object, in which the pageUrl variable is to be loaded The URL of the page. The page content returned by the server will be displayed in the element with the id content.

In addition, Ajax can also interact with the server for data, allowing the web page to update data in real time without refreshing. The following is an example of obtaining server data in real time through Ajax:

function updateData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.responseText);
      document.getElementById("data").innerHTML = data.value;
    }
  };
  var url = "data.json";
  xhttp.open("GET", url, true);
  xhttp.send();
}

// 每隔一段时间调用updateData函数
setInterval(updateData, 5000); // 每5秒更新一次

Through the above code, the page will obtain data from the server every 5 seconds, and then display the data in the id data element. This achieves the effect of updating data in real time.

In addition to GET requests, Ajax also supports POST requests. POST requests are often used to submit form data to the server. The following is an example of using Ajax to send a POST request:

function postData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = this.responseText;
      document.getElementById("result").innerHTML = response;
    }
  };
  var data = new FormData();
  data.append('username', 'john');
  data.append('password', '123456');
  xhttp.open("POST", "login.php", true);
  xhttp.send(data);
}

In the above code, the FormData object is used to store the data that needs to be sent. When the third parameter in the open function is set to true, the request will become asynchronous, that is, an Ajax request.

Through the above code examples, I believe readers will have a deeper understanding of the functions of Ajax. It is worth mentioning that in order to ensure browser compatibility, JavaScript libraries such as jQuery can be used to simplify Ajax operations.

To summarize, Ajax is powerful and can help us dynamically load content, obtain server data in real time, and submit forms. By using Ajax, we can improve the interactivity and response speed of web pages and provide users with a better experience. I hope the specific code examples in this article can help readers better understand and use Ajax technology.

The above is the detailed content of Revealing the power of Ajax. 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
PHP中Request的作用及意义PHP中Request的作用及意义Feb 27, 2024 pm 12:54 PM

PHP中Request的作用及意义在PHP编程中,Request是指向Web服务器发送请求的一种机制,它在Web开发中起着至关重要的作用。Request主要用于获取客户端发送过来的数据,比如表单提交、GET或POST请求等,通过Request能够获取到用户输入的数据,并对这些数据进行处理和响应。本文将介绍PHP中Request的作用及意义,并给出具体的代码示

哪些JS事件不会向上冒泡?哪些JS事件不会向上冒泡?Feb 19, 2024 pm 09:56 PM

JS事件中有哪些不会冒泡的情况?事件冒泡(EventBubbling)是指在触发了某个元素的事件后,事件会从最内层元素开始沿着DOM树向上传递,直到最外层的元素,这种传递方式称为事件冒泡。但是,并不是所有的事件都能冒泡,有一些特殊情况下事件是不会冒泡的。本文将介绍在JavaScript中有哪些情况下事件不会冒泡。一、使用stopPropagati

Vue中如何实现表单的校验和提交Vue中如何实现表单的校验和提交Oct 15, 2023 am 11:14 AM

Vue中如何实现表单的校验和提交在Web开发中,表单是用户与网页进行交互的重要界面,表单中用户输入的数据需要进行校验和提交,以确保数据的合法性和完整性。Vue.js是一个流行的前端框架,它提供了便捷的表单校验和提交方法,使我们能够快速地实现表单功能。本文将介绍如何使用Vue.js来实现表单的校验和提交,并提供具体的代码示例。一、表单校验安装vee-valid

攻克 CSRF 难关:万无一失的 PHP 防护策略攻克 CSRF 难关:万无一失的 PHP 防护策略Feb 25, 2024 pm 01:20 PM

2.1使用CSRFTokenCSRFToken是一个随机生成的字符串,在用户会话中生成并存储,并在每个请求中随表单或链接一起发送。当服务器收到请求时,会验证CSRFToken是否与会话中的Token一致,如果不一致,则认为是CSRF攻击,并拒绝请求。2.2使用RefererHeaderRefererHeader是一个Http请求头,包含了请求来源的URL。服务器可以检查RefererHeader来确定请求是否来自合法来源。如果RefererHeader不存在或指向一个不合法来源,则认为是CSRF

如何在PHP中使用WebSockets API进行实时视频和音频聊天如何在PHP中使用WebSockets API进行实时视频和音频聊天Jun 17, 2023 pm 02:37 PM

WebSocketsAPI是实现实时视频和音频聊天的重要组成部分,它提供了一种基于事件驱动机制的通信方式,可以实现双向通信,使得浏览器与服务器之间的通信更加简单、快速和安全。本文将介绍如何在PHP中使用WebSocketsAPI进行实时视频和音频聊天。安装WebSocket服务器在PHP中使用WebSocketsAPI,首先需要安装WebSocket服

使用jQuery获取另一JSP页面传递的参数使用jQuery获取另一JSP页面传递的参数Feb 26, 2024 am 11:54 AM

标题:使用jQuery查询另一个JSP页面传递的参数在开发Web应用程序时,经常会遇到需要在一个JSP页面中获取另一个JSP页面传递过来的参数的情况。这时候,可以借助jQuery来实现这一功能。下面将介绍如何使用jQuery查询另一个JSP页面传递的参数,并给出具体的代码示例。首先,我们需要明确一点,JSP页面之间传递参数一般有两种方式:一种是通过URL参数

Vue中的v-on指令解析:如何处理表单提交事件Vue中的v-on指令解析:如何处理表单提交事件Sep 15, 2023 am 09:12 AM

Vue中的v-on指令解析:如何处理表单提交事件在Vue.js中,v-on指令用于绑定事件监听器,可以捕获并处理各种DOM事件。其中,处理表单提交事件是Vue中常见的操作之一。本文将介绍如何使用v-on指令处理表单提交事件,并提供具体的代码示例。首先,需要明确Vue中的表单提交事件指的是当用户点击submit按钮或按下回车键时触发的事件。在Vue中,可以通过

如何结合Layui和jQuery打造优质网页?如何结合Layui和jQuery打造优质网页?Feb 22, 2024 pm 11:15 PM

如何结合Layui和jQuery打造优质网页?随着互联网技术的不断发展,前端开发也变得愈加重要。而Layui和jQuery作为两个常用的前端框架,它们的结合能够为网页开发带来更好的体验和更丰富的功能。本文将介绍如何结合Layui和jQuery打造优质网页,并提供具体的代码示例。Layui和jQuery介绍Layui是一款经典的前端UI框架,它提供了丰富的UI

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.