Analysis of Ajax technology composition and core principles
This article mainly introduces the function throttling (throttle) and function debounce (debounce) of JavaScript performance optimization. Interested friends can refer to it.
This article mainly analyzes Ajax technology for everyone. The composition principle is for your reference. The specific content is as follows
1. Ajax
##Features:Partial refresh, improve user experience , data is loaded from the server provider
2. The technical composition of AJax
is not a new technology, but the integration of previous technologiesAjax: Asynchronous Javascript And Xml; (Asynchronous JavaScript and XML)
Included technologies: JavaScript, XML, CSS, XMLHttpRequest
Asynchronous: After sending the request, the result is processed by the callback function.
JavaScript: Send a request to the server, obtain the return result, and update the page
XML: Used to encapsulate data
XMLHttpRequst object : Send a request to the server through this object.
It is an asynchronous request technology, supported by all modern browsers (Chrome, IE5)
Non-IE browsers (Mozilla/Safari) :var xhr=new XMLHttpRequest();
IE:xhr=new ActiveXObject("Msxml2.XMLHTTP");Lower version IE:xhr=new ActiveXObject("Microsfot.XMLHTTP");
2) Properties and methods of XMLHttpRequest object
a) Method: open("GET/POST", URL, true/false): used to establish a connection to the server
There are three parameters: Parameter 1: Submission method, post or get
Parameter 2: Requested URL
Parameter 3: Indicates synchronous or asynchronous request, true: indicates asynchronous request
false: Indicates synchronous request
send(data) :Send request
Parameters: Submitted content.
POST method: data is the submitted parameter, send(username=root&password=abc123);
GET method: send(null)
b) Attribute:
onreadystatechange=function(){
}
readyState: Server status response
Status code:
0: Not initialized
1: Loading 2: Loading completed
3: Request in progress
4: Request completed
responseText: Data returned by the server (text format)
Steps to use XMLHttpRequest: 1) Create XMLHttpRequest object
2) Set the request method and URL
xhr. open("GET/POST","url",true/false), true represents an asynchronous request, false represents a synchronous request
3) Set the callback function when the state changes
xhr.onreadystatechange=function(){}
0: Not initialized
1: Loading
2: Loading completed
3: Request in progress
4: Request completed
4) Send request
xhr.send( data),
If submitted for post, data is the submitted data. If submitted for get, the parameter can be null.
Determine the HTML page the user logged in:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录</title> </head> <body> 用户名:<input type="text" name="username" id="username"><br> 密码:<input type="password" name="password" id="password"> <a href="javascript:chkUser();">登录</a> <p id="res"></p> </body> <script type="text/javascript"> var xhr; /** * 创建XMLHttpRequest对象 */ function createXMLHttpRequest(){ //1、创建XMLHttpRequest对象 if(window.XMLHttpRequest){ //非IE内核浏览器 xhr=new XMLHttpRequest(); }else{ //IE浏览器 try{ xhr=new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ //IE低版本 xhr=new ActiveXObject("Microsoft.XMLHTTP"); } } } /** * 发送请求,用来检查用户名、密码是否正确 */ function chkUser(){ //1、创建XMLHttpRequest createXMLHttpRequest(); //2、获得用户名、密码 var username=document.getElementById("username").value; var password=document.getElementById("password").value; //3、与服务器建立连接:open var url="login?username="+username+"&password="+password; //方式1:get提交 //xhr.open("GET",url,true); //方式2:post提交 var url2="login"; xhr.open("POST",url2,true); //4、设置回调函数,获得服务器响应的数据 xhr.onreadystatechange=function(){ /* readyState状态码: 0:未初始化 1:正在加载 2:加载完成 3:请求进行中 4:请求完成 */ if(xhr.readyState==4){ //status,200表示响应正常 if(xhr.status==200){ //alert("从服务器返回的值为:"+xhr.responseText); var res=xhr.responseText; if(res=='0'){ document.getElementById("res").innerHTML="登录成功"; }else{ document.getElementById("res").innerHTML="<font color='red'>登录失败</font>"; } }else{ alert("出现在了异常:"+xhr.response.Text); } } } //5、发送请求 //方式1:get方式 //xhr.send(null); //方式2:post方式: //Post提交需要设置http请求头 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("username="+username+"&password="+password); } </script> </html>
Server code:
package com.newer.login.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.newer.login.bean.User; import com.newer.login.service.UserService; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; UserService userService = new UserService(); /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1、获得页面参数 String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("获得请求的参数username:"+username); System.out.println("获得请求的参数password:"+password); // 2、封装User对象 User user = new User(); user.setUsername(username); user.setPassword(password); // 3、调用服务类,完成用户名、密码的校验 User u = userService.login(user); /* * 传统方式 if(u!=null){ //表示登录成功 request.setAttribute("user", user); * //跳转至首页... }else{ //登录失败,跳转登录页面 * * } */ // ajax响应 PrintWriter out = response.getWriter(); if (u != null) { //0成功,1失败 out.print(0); }else{ out.print(1); } out.close(); } }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Ajax asynchronous loading analysisAjax synchronous method to verify whether the order number existsAjax implementation method to obtain data and then display it on the page##
The above is the detailed content of Analysis of Ajax technology composition and core principles. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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.

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.

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

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


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

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

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.