search
HomeWeb Front-endJS TutorialDetailed graphic and text explanation of AJAX usage tutorial (with video)

This time I will bring you a detailed explanation of the use of AJAX in the graphic tutorial. What are the precautions for using AJAX in the graphic tutorial? The following is a practical case, let’s take a look.

The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server, making user operations and server responses asynchronous. There are many principles for introducing ajax on the Internet. This article will give you a more direct and clear introduction in the form of pictures and texts. If you need it, you can refer to it.

Recommended related video tutorials: " Quick Introduction to PHP and Ajax"

First go to the schematic diagram:

Background:

1. For traditional Web websites, submitting a form requires reloading the entire page.

2. If the server fails to return Response for a long time, the client will become unresponsive and the user experience will be very poor.

3. After the server returns the Response, the browser needs to load the entire page, which is also a heavy burden on the browser.

4. After the browser submits the form, a large amount of data is sent, causing network performance problems.

Question:

1. How to improve?

2.What is AJAX?

3. What are the advantages?

4. What are the disadvantages?

1. What is AJAX

1. Why AJAX is needed

When you need to access the server To obtain data and refresh the page, if AJAX is not used, you need to submit the entire form. When the form is submitted, a request is sent to the server. The page needs to wait for the server to send the response before the page can resume operations.

2. The concept of AJAX:

1.AJAX = Asynchronous JavaScript and XML.

2.AJAX is a technology used to create fast dynamic web pages.

3. By exchanging a small amount of data with the server in the background, the web page can be updated asynchronously.

4. You can update certain parts of the webpage without reloading the entire webpage.

3. What is asynchronous

The current page sends a request to the server. The current page does not need to wait for the server response to operate the web page. After sending the request, the current page can continue to be browsed and operated.

4. What is partial refresh?

We can achieve partial refresh in two ways.

1. How to reload the iframe page.

Although this method achieves partial refresh, it is a reload of the page, so it will also cause performance problems.

Step1. Define an Iframe in the page

<iframe></iframe>

Step2. Set the src of the Iframe

var indexFrame = document.getElementById("indexFrame");
indexFrame.src = "introduction.php";

Step3. Add a button click Event , when this button is clicked, the src of the Iframe is reset to refresh the page in the iframe. Content outside the Iframe is not refreshed.

<button>Click Me!</button>
rrree

In this way we can implement the function of a navigation bar:

  

 2.AJAX method

Step 1. JavaScrpit sends an asynchronous request

Step 2. The server queries the database and returns data

Step 3. The server returns Response

Step 4. The client responds to the response Manipulate the DOM with JavaScript.

Look at the example below:

  当我们切换DropDownList中的Item时,JavaScript发送异步请求给Server端,Server端返回数据,然后JavaScript将数据解析出来,拼接了一个Table,将Table呈现在页面上。

二、提交Form表单的原理

1.代码

客户端代码:


   您的姓名1:      

服务端代码:

public void ProcessRequest (HttpContext context)
{
  //Delay
  for (int i = 0; i <p style="text-align: left;"><strong>2.将代码部署到IIS</strong></p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/d2d80f980ee662ef5d88f355884f75d2-3.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"><strong>3.打开站点:</strong></p><p style="text-align: left;">http://localhost:8003/Test.html</p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/d2d80f980ee662ef5d88f355884f75d2-4.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"><strong>4.输入“Jackson0714”然后点击Sumbit按钮</strong>,页面会重新刷新,显示"Hello World Jackson0714"</p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/d2d80f980ee662ef5d88f355884f75d2-5.gif?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"><strong>5.提交Form表单后</strong>,页面发送请求和服务端返回响应的流程 </p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/f29860dd83a72c2d0a47f2302e044be0-6.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"><strong>6.通过抓包</strong>,我们可以得到HTTP Headers</p><p style="text-align: left;">浏览器发送HTTP给服务端,采取的协议是HTTP协议。</p><p style="text-align: left;">在传输过程中,我们可以看下HTTP Headers。</p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/f29860dd83a72c2d0a47f2302e044be0-7.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"><span style="color: #ff0000"><strong> 三、AJAX提交请求和服务响应的原理</strong></span></p><p style="text-align: left;"><strong>1.代码</strong></p><p style="text-align: left;">客户端HTML代码:</p><pre class="brush:php;toolbar:false">nbsp;html>
 


 <meta>
 <title></title>
 <script></script>
 


 <p>
  您的姓名2:<input>
  <button>Ajax Get请求</button>
 </p>
   
 <p>
  您的姓名3:<input>
  <button>Ajax Post请求</button>
 </p>
 
 <p></p>
 

客户端JS代码:

var xmlhttp = createRequest();
 
function testGet() {
 var fname = document.getElementById("testGetName").value;
 xmlhttp.open("GET", "Test.ashx?fname=" + fname + "&random=" + Math.random() , true);
 xmlhttp.onreadystatechange = callback;
 xmlhttp.send(null);
}
 
function testPost() {
 var fname = document.getElementById("testPostName").value;
 xmlhttp.open("POST", "Test.ashx?" + "&random=" + Math.random() , true);
 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
 xmlhttp.onreadystatechange = callback;
 xmlhttp.send("fname="+fname);
 
}
 
function createRequest() {
 var xmlhttp;
 if (window.XMLHttpRequest) {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();
 }
 else {
  // code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 return xmlhttp
}
 
function callback() {
 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  document.getElementById("myp").innerHTML = xmlhttp.responseText;
 }
}

这里有一点需要注意

var xmlhttp = createRequest(); 。

       1.让服务端能够操作这个变量,如果定义成局部变量,则服务端返回response时,不能对xmlhttp的属性赋值。回调函数要求request是全局的,才能访问这个变量和它的属性值。

       2.定义成全局变量后,可能出现两个请求或多个请求共享同一个请求对象。而这个请求对象只能存放一个回调函数来处理服务器响应。当服务器返回两个请求的Response后,可能会调用后指定的回调函数。所以可能有两个完全不同的服务器响应由同一个回调函数处理,而这可能并不是正确的处理。解决办法是创建两个不同的请求对象。 

服务端代码不变。

2.输入“Jackson0714”然后点击Sumbit按钮,页面不会刷新,在最下面显示"Hello World Jackson0714"

3.AJAX发送请求和服务端返回响应的流程

 

4.通过抓包,我们可以得到HTTP Headers

浏览器发送HTTP给服务端,采取的协议是HTTP协议。

在传输过程中,我们可以看下HTTP Headers:

 

5.AJAX  GET和POST方式区别

AJAX发送请求和POST发送请求的代码如下:

//GET方式
function testGet() {
 var fname = document.getElementById("testGetName").value;
 xmlhttp.open("GET", "Test.ashx?fname=" + fname + "&random=" + Math.random() , true);
xmlhttp.onreadystatechange = callback;
 xmlhttp.send(null);
}
 
//POST方式
function testPost() {
 var fname = document.getElementById("testPostName").value;
 xmlhttp.open("POST", "Test.ashx?" + "&random=" + Math.random() , true);
 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
 xmlhttp.onreadystatechange = callback;
 xmlhttp.send("fname="+fname);
 
}

四、XMLHttpRequest 对象的知识

1.XMLHttpRequest 对象的方法

 2.XMLHttpRequest 对象的属性

五、JQuery实现AJAX

下面的代码实现了当切换DropDownList的item时,触发getWeeklyCalendar方法,用JQuery的类库方法$.ajax来发送AJAX请求。

客户端JQuery代码

function getWeeklyCalendar(name,currentDate,mode){
 $.ajax({
  type:'POST',
  url:'weekProcess.php',data:'func=getWeeklyCalender&name='+name+'&currentDate='+currentDate+'& mode='+mode,
  success:function(data){
  paintWeeklyCandler(data);
  }
 });
}

后台成功返回Response后,执行paintWeeklyCandler(data)方法

后台PHP代码

<?php <br> //定义返回的Response的格式为JSON格式
 header('Content-type: text/json');<br> //引入自定义的数据库连接文件
 include 'dbConfig.php';<br> //引入自定义的设置session的文件
 include_once 'session.php';
 /*
 * Function requested by Ajax
 */
 if(isset($_POST['func']) && !empty($_POST['func']))
 {
  switch($_POST['func']){
    case 'getWeeklyCalender':
      getWeeklyCalender($_POST['name'],$_POST['currentDate'],$_POST['mode']);
       break;
     case 'getWeeklyStatus':
      getWeeklyStatus($_POST['name'],$_POST['currentDate'],$_POST['mode']);
      break;
     case 'getEvents':
      getEvents($_POST['date'],$_POST['name']);
      break;
    default:
      break;
 }
}
 function getWeeklyCalender($name = '',$currentDate = '',$mode = '')
 {
  //逻辑代码<br>    <br>  <br>    //返回JSON格式的Response
  echo json_encode(array('result'=>$DaysOfWeekResultsArray));
 }<br>?>

六、优势

     1.使用异步方式与服务器通信,页面不需要重新加载,页面无刷新

     2.按需取数据,减少服务器的负担

     3.使得Web应用程序更为迅捷地响应用户交互

     4.AJAX基于标准化的并被广泛支持的技术,不需要下载浏览器插件或者小程序,但需要客户允许JavaScript在浏览器上执行

     5.浏览器的内容和服务端代码进行分离。页面的内容全部由JAVAScript来控制,服务端负责逻辑的校验和从数据库中拿数据。

七、缺点

     1.安全问题:将服务端的方法暴露出来,黑客可利用这一点进行攻击

     2.大量JS代码,容易出错

     3.Ajax的无刷新重载,由于页面的变化没有刷新重载那么明显,所以容易给用户带来困扰——用户不太清楚现在的数据是新的还是已经更新过的;现有的解决有:在相关位置提示、数据更新的区域设计得比较明显、数据更新后给用户提示等

     4.可能破坏浏览器后退按钮的正常行为;

     5.一些手持设备(如手机、PAD等)自带的浏览器现在还不能很好的支持Ajax

八、应用场景

     1.对数据进行过滤和操纵相关数据的场景

     2.添加/删除树节点

     3.添加/删除列表中的某一行记录

     4.切换下拉列表item

     5.注册用户名重名的校验

九、不适用场景

     1.整个页面内容的保存

     2.导航

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax在不刷新的情况下实现评论功能

Ajax概述与实现

The above is the detailed content of Detailed graphic and text explanation of AJAX usage tutorial (with video). 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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use