


Detailed graphic and text explanation of the underlying principles of AJAX
This time I will bring you a detailed explanation of the underlying principles of AJAX with pictures and texts, what are the notes when using the underlying principles of JAX, the following is a practical case, let's take a look.
First 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 you do not use AJAX, 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 web page without reloading the entire web page.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 id="indexFrame" name="index" width="1000" height="800" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="margin-top:100px;"></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 id="room" onclick='IndexClick("room")'>Click Me!</button>
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 returned Response Manipulate the DOM with JavaScript. Look at the following example:2. Principle of submitting Form form
1. Code
客户端代码:
<form id="form1" action="Test.ashx" method="get"> 您的姓名1:<input type="text" name="fname" size="20" /> <input type="submit" name="submit" value="Sumbit"> </form>
服务端代码:
public void ProcessRequest (HttpContext context) { //Delay for (int i = 0; i < 2; i++) { System.Threading.Thread.Sleep(1000); } //从Requset.Form中获取fname的值。使用Form获取请求的键值对的值的前提条件是HTTP request Content-Type 值必须是"application/x-www-form-urlencoded" 或 "multipart/form-data". string fname = context.Request["fname"]; context.Response.ContentType = "text/plain"; //将字符串写入 HTTP 响应输出流。 context.Response.Write("Hello World " + fname); }
2.将代码部署到IIS
3.打开站点:
http://localhost:8003/Test.html
4.输入“Jackson0714”然后点击Sumbit按钮,页面会重新刷新,显示"Hello World Jackson0714"
5.提交Form表单后,页面发送请求和服务端返回响应的流程
6.通过抓包,我们可以得到HTTP Headers
浏览器发送HTTP给服务端,采取的协议是HTTP协议。
在传输过程中,我们可以看下HTTP Headers。
三、AJAX提交请求和服务响应的原理
1.代码
客户端HTML代码:
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript" src="Ajax.js"></script> </head> <body> <p id="Test" style="background-color:#40eeee"> 您的姓名2:<input type="text" id="testGetName" size="20" /> <button type="button" onclick="testGet();">Ajax Get请求</button> </p> <p id="Test" style="background-color:#ff6a00"> 您的姓名3:<input type="text" id="testPostName" size="20" /> <button type="button" onclick="testPost();">Ajax Post请求</button> </p> <p id="myp" /> </body> </html>
客户端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+'¤tDate='+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中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed graphic and text explanation of the underlying principles of AJAX. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

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 solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

The RPM (RedHatPackageManager) tool in Linux systems is a powerful tool for installing, upgrading, uninstalling and managing system software packages. It is a commonly used software package management tool in RedHatLinux systems and is also used by many other Linux distributions. The role of the RPM tool is very important. It allows system administrators and users to easily manage software packages on the system. Through RPM, users can easily install new software packages and upgrade existing software
