This article mainly shares with you the principle of graphic and text analysis AJAX. The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server, so that the user operation and the server response are asynchronous. There are many principles for introducing ajax on the Internet, I hope it can help everyone.
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 is AJAX needed
When you need to obtain data from the server and refresh the page, if you do not use For 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 iframe pages.
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 the button is clicked, re- Set the src of the Iframe to refresh the page in the iframe. Content outside the Iframe is not refreshed.
<button>Click Me!</button>
function IndexClick(moduleKey) { var indexFrame = document.getElementById("indexFrame"); if(indexFrame == null) { indexFrame = parent.document.getElementById("indexFrame"); } var url = "introduction.php"; switch (moduleKey) { case "introduction": url = "introduction.php"; break; case "room": url = "room.php"; break; default: { } } indexFrame.src = url; }
In this way we can implement the function of a navigation bar:
2.AJAX method
Step1.JavaScrpit sends asynchronously Request
Step2. The server queries the database and returns data
Step3. The server returns Response
Step4. The client uses JavaScript to operate the DOM based on the returned Response.
Look at the following example:
When we switch the Item in the DropDownList, JavaScript sends an asynchronous request to the Server side, the Server side returns the data, and then JavaScript The data is parsed, a Table is assembled, and the Table is presented on the page.
2. Principle of submitting Form form
1. Code
Client code:
Server code:
public void ProcessRequest (HttpContext context) { //Delay for (int i = 0; i <p>2. Deploy the code to IIS</p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/cd7bb293ecc54b225ede5eee33e2ad31-3.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p>3. Open the site: </p><p>http://localhost:8003/Test.html </p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/cd7bb293ecc54b225ede5eee33e2ad31-4.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p></p>##4. Enter "Jackson0714" and click the Sumbit button. The page will refresh and display "Hello World Jackson0714"<p></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/cd7bb293ecc54b225ede5eee33e2ad31-5.gif?x-oss-process=image/resize,p_40" class="lazy" alt=""></p>5. After submitting the Form form, the page sends a request and the server returns a response. <p></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/1ef3c71988b30dfe90db6c2b091ee300-6.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p>6. By capturing the packet, we can get the HTTP Headers<p><br></p>The browser sends HTTP to the server, and the protocol adopted is the HTTP protocol. <p></p>During the transmission process, we can look at the HTTP Headers. <p></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/1ef3c71988b30dfe90db6c2b091ee300-7.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p> 3. The principle of AJAX submission request and service response<p><br></p>1. Code<p></p>Client HTML code:<p></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>Client JS code:
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; } }There is one thing to note herevar 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.导航
十、总结
以上就是本文的全部内容,文章写的很详细,希望对大家学习ajax能有所帮助哦。
相关推荐:
The above is the detailed content of Graphical analysis of AJAX principle sharing. For more information, please follow other related articles on the PHP Chinese website!

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById('fileBox').files[0];varreader=newFileReader();reader.readAsText(file,'UTF-8');reader.onload=myFunc;functionmyFunc(event){ varres

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
