search
HomeBackend DevelopmentPHP TutorialGraphical analysis of AJAX principle sharing

Graphical analysis of AJAX principle sharing

Jan 12, 2018 pm 04:24 PM
ajaxshareprinciple

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:


   您的姓名1:      

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 here

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.导航

十、总结

以上就是本文的全部内容,文章写的很详细,希望对大家学习ajax能有所帮助哦。

相关推荐:

有关对Ajax的原理以及代码封装实例详解

AJAX原理与CORS跨域的方法

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!

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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.