Ajax (asynchronousjavascriptandxml) asynchronous javascript and xml.
It is to solve the shortcomings of the "send request-wait for response" model in traditional web applications. (After sending the request, the browser can only wait for the server's response. The user cannot do other operations. After the browser sends the request, will abandon the entire page and wait for the server to return a new page. In other words, the amount of data interacted between the browser and the server is very large and data cannot be obtained on demand). The essence of this technology is: through a An object (XmlHttpRequest) built into the browser sends a request to the server asynchronously.
The so-called asynchronous means that the browser does not abandon the entire page, that is, it does not send data to the server through form submission. After the server processes the request, it returns the data to the XmlHttpRequest object, and the data in the XmlHttpRequest can be obtained through javascript. Then, Use this data to update the page. During the entire process, the user does not have to wait for a response from the server.
Description: Asynchronous transmission technology of web pages. A method to communicate with the server without refreshing the entire page. While waiting for the transmission of the web page, the user can still interact with the system, and the page can update the content without refreshing. Reasonable use can allow It feels better and more convenient for users, but don’t abuse it
Synchronous and asynchronous
Synchronization refers to the communication method in which the sender sends data and waits for the receiver to send back a response before sending the next data packet.
Eg. Synchronization: submit request -> wait for server processing -> return after processing. During this period, the client browser cannot do anything. Asynchronous means: after the sender sends the data, it does not wait for the receiver to send back a response, and then sends the next data packet. communication method
Eg. Asynchronous: The request is triggered by an event -> processed by the server (the browser can still do other things at this time) -> processed
Important object of AjaxXMLHttpRequest
Important Javascript object, through which requests to the server can be made. Requests can be made through Javascript. If multiple requests are to be made, multiple XHR objects are required. The result of the request is processed by a predefined method.
How to create an XmlHttpRequest object
function getXmlHttpRequest(){
var xmlHttpRequest = null;
if ((typeof XMLHttpRequest) != 'undefined') {
//non-ie browser
xmlHttpRequest = new XMLHttpRequest();
}else {
//ie browser
xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp');
}
return xmlHttpRequest;
}
or
function createXmlHttpRequest(){
var xmlHttpRequest = null;
if(window.ActiveXObject){
xmlHttpRequest = new AvtiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttpRequest = new XMLHttpRequest();
}
}
Important properties of the xmlHttpRequest object.
responseXml: Get the xml data of the server response
status: Get the status code returned by the server (such as 200)
readyState: Get the status of communication between xmlHttpRequest and the server (0, 1, 2, 3, 4, respectively describing different states).
(Uninitialized): The object has been created, but has not been initialized (the open method has not been called yet)
(Initialization): The object has been created and the send method has not been called yet.
(Send data): The send method has been called, but the current status and http header are unknown
(Data transmission in progress): Partial data has been accepted.
(End of response): At this point, data can be obtained through responseText/responseXml.
An application example implemented by a person using Ajax
System screenshot
System description:
System structure diagram
Display the front page register.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>User registration</title>
<link href="css/regist.css" rel="stylesheet" type="text/css" />
<script src="js/regist_ajax.js" type="text/javascript"></script>
</head>
<body onload="getRegistRuleTxt(),getCheckcode()">
<form action="regist.do" onsubmit="return check(this);">
<table bordercolor="gray" cellpadding="6" align="center">
<tr>
<td colspan="2">
>> <font color="red">User registration</font>
<font color="gray">[Module description: User name check, terms of service use Ajax asynchronous processing, verification code server generation]</font>
</td>
</tr>
<tr>
<td align="right">
username:
</td>
<td>
<input type="text" name="username" id="username" onblur="postValidate()"/>
<span style="color:orange" id="checkMsg" > * The username consists of letters, numbers, and underscores.</span>
</td>
</tr>
<tr>
<td align="right">
password:
</td>
<td>
<input type="password" name="password" id="password">
<span style="color:orange" id="pwdMsg" > * The password length is 6-8 characters. For security, unique formats should be avoided.</span>
</td>
</tr>
<tr>
<td align="right">
Confirm Password:
</td>
<td>
<input type="password" name="repassword" id="repassword">
<span style="color:orange" id="repwdMsg" > * Confirm the password to ensure that you made no mistake when setting the password</span>
</td>
</tr>
<tr>
<td align="right">
Mail:
</td>
<td>
<input type="text" id="email" name="email">
<span style="color:orange" id="emailMsg" > * Enter your usual email address so that we can contact you.</span>
</td>
</tr>
<tr>
<td align="right">
Verification code:
</td>
<td>
<input type="text" id="checkcode">
<img id="ckcodeimage" src="imgsrc" style="border:solid #92CEDB 1px "> <!-- Verification code-->
<a href="javascript:;" onclick="getCheckcode()">Can't see clearly, change another one</a>
<span style="color:orange" id="ckcodeMsg" > </span>
</td>
</tr>
<tr>
<td align="right">
Terms of Service:
</td>
<td>
<textarea rows="5" cols="48" style="margin-bottom:6px;margin-left:5px; color:gray" readonly="readonly" id="item" >
</textarea>
</td>
</tr>
<tr>
<td align="right">
</td>
<td>
<input type="submit" value="Agree the terms and register"/>
</td>
</tr>
</table>
<div align="center">
Copyright (c) 2013 Su Ruonian ( <a href="mailto:[email protected]">Contact us:[email protected]</a> )
corporation All Rights Reserved.
</div>
</form>
</body>
</html>
/*
Create a method to obtain the xmlHttpRequest object
*/
function getXmlHttpRequest(){
var xmlHttpRequest = null;
if((typeof XMLHttpRequest) != 'undefined'){
/*Non-IE browsers create XMLHttpRequest objects*/
xmlHttpRequest = new XMLHttpRequest();
}else{
/*IE browser creates XMLHttpRequest object*/
xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp');
}
return xmlHttpRequest;
}
/*
Verification code response event
*/
function getCheckcode(){
var codeimage = document.getElementById("ckcodeimage");
var url = "checkcode.do";
codeimage.src=addTimestamp(url);
}
/*
Using Ajax to get terms of service
*/
function getRegistRuleTxt(){
var item = document.getElementById("item");
var url = "rulesText.do";
//Solve the Chinese encoding problem when submitting in get mode. Use encodeURI(url).true to indicate that the request is sent asynchronously, and addTimestamp(url) prevents browser caching.
xmlHttpRequest.open("post",encodeURI(url),true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.onreadystatechange=function(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var respText = xmlHttpRequest.responseText;
item.value=respText;
}else{
//System error.
item.value="system error";
}
}else{
//Display checking...
item.value="loading...";
}
};
xmlHttpRequest.send(null);
}
/*
Use get method to verify
*/
function getValidate(){
var username = document.getElementById("username");
var url = "validatename.do?username=" + username.value;
//Solve the Chinese encoding problem when submitting in get mode. Use encodeURI(url).true to indicate that the request is sent asynchronously, and addTimestamp(url) prevents browser caching.
xmlHttpRequest.open("get",encodeURI(addTimestamp(url)),true);
//Call the method to check the return status
xmlHttpRequest.onreadystatechange=callback;
xmlHttpRequest.send(null);
}
/*
Use post method to verify
*/
function postValidate(){
var username = document.getElementById("username");
var url = "validatename.do";
//true means using an asynchronous method to send the request. The default is true, and the request method can be get, post, put, delete
xmlHttpRequest.open('post',url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.onreadystatechange=callback;
//If there are multiple parameters, use the & symbol to link key-value pairs, and escape is used to solve Chinese problems
xmlHttpRequest.send('username=' + escape(username.value));
}
/*
Monitoring status return method
*/
function callback(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var respText = xmlHttpRequest.responseText;
innerHtmlMsg(respText);
}else{
//System error.
innerHtmlMsg("error");
}
}else{
//Display checking...
innerHtmlMsg("checking");
}
}
/*
Add timestamp to prevent browser caching. Browser caching only caches the get method.
*/
function addTimestamp(url){
if(url.indexOf("?")!=-1){
//If there are parameters
return url+"×tamp=" + new Date().valueOf();
}else{
//no parameters
return url+"?timestamp=" + new Date().valueOf();
}
}
function innerHtmlMsg(message){
var checkMsg = document.getElementById("checkMsg");
if(message=='exists'){
//Username exists
checkMsg.innerHTML= "<font color='red'>* Sorry, the username already exists.</font>";
}
if(message=='noexists'){
//Username can be used
checkMsg.innerHTML= "<font color='green'>* Congratulations, the username is available.</font>";
}
if(message=='checking'){
//System checking
checkMsg.innerHTML= "<font color='#0099aa'>* The system is checking data...</font>";
}
if(message=='error'){
//System error
checkMsg.innerHTML= "<font color='red'>System failure, please check the network, or <a href='#'>Contact us</a></font>";
}
}
} /* Define the overall width and border style of the table, and define the style of all text in the table */
.left{
font-weight:500;
color:#708899;
padding-right:20px;
background-color: #D6ECF5;
}
.inpt {
border:solid #92CEDB 1px;
width: 210px;
height: 22px;
margin-left: 10px;
}
.rghts{
margin-top:20px;
color:#708899;
font-size:12px;
}
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.webapp.servlet.UserServlet</servlet-class>
<init-param>
<param-name>rulesfilepath</param-name>
<param-value>/txt/item.txt</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>regist.jsp</welcome-file>
</welcome-file-list>
</web-app>
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-1-20 04:26:52 pm
*
* @function: TODO
*
*/
public class CheckCodeImageUtil {
private static final String[] chars = { "0", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I" };
private static final int SIZE = 4; //The number of characters in the verification code
private static final int LINES = 4; //number of interference lines
private static final int WIDTH = 110; //Verification code image width
private static final int HEIGHT = 40; //Verification code picture height
private static final int FONT_SIZE = 21; //Font size on verification code
/**
* Generate verification code
*
* @return Map<value of verification code, picture of verification code>
*
*/
public static Map<String,BufferedImage> creatCheckImage(){
//Save the string that generates the true value of the verification code
StringBuffer buffer = new StringBuffer();
//Custom image object
BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Map<String,BufferedImage> map = new HashMap<String,BufferedImage>();
Graphics graphics = image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
Random random = new Random();
//Draw random characters
for(int i=0; i<SIZE; i++){
//Get an element from the defined character set
int rand = random.nextInt(chars.length);
graphics.setColor(randomColor());
graphics.setFont(new Font(null,Font.BOLD+Font.ITALIC,FONT_SIZE));
graphics.drawString(chars[rand],(i)*WIDTH/SIZE+8, HEIGHT/2+10);
buffer.append(chars[rand]); //Save the generated string into the buffer and use it to compare with the value entered by the user when obtained in the future.
}
//Draw interference lines
for(int i=1;i<=LINES;i++){
graphics.setColor(randomColor());
graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH),random.nextInt(HEIGHT));
if(i==LINES){
graphics.setFont(new Font(null,Font.ITALIC,13));
graphics.setColor(Color.GRAY);
graphics.drawString("Su Ruonian Studio", 5,15);
}
}
map.put(buffer.toString(), image);
return map;
}
/**
* Color will be generated immediately
* @return
*/
public static Color randomColor(){
Random random = new Random();
Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
return color;
}
}
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.imageio.plugins.common.ImageUtil;
import com.webapp.util.CheckCodeImageUtil;
public class UserServlet extends HttpServlet {
private List<String> userList;
private String txtFilePath = null;
public void init() throws ServletException {
txtFilePath = this.getInitParameter("rulesfilepath");
//Simulate database
userList = new Vector<String>();
userList.add("zhangsan");
userList.add("lisi");
userList.add("wangwu");
userList.add("zhaoliu");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
if(path.equals("/validatename")){
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Simulation system generates exception test
/*if(1==2){
throw new ServletException("some error");
}*/
String username = request.getParameter("username");
System.out.println("username:" + username);
//Simulate user data query
boolean exist = userList.contains(username);
if(exist){
response.getWriter().print("exists");
}else{
response.getWriter().print("noexists");
}
}
if(path.equals("/rulesText")){
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String filePath = this.getServletContext().getRealPath(txtFilePath);
File file = new File(filePath);
StringBuffer buffer = new StringBuffer();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String tmp = "";
while((tmp = reader.readLine())!=null){
buffer.append(new String(tmp.getBytes("gbk"),"utf8")).append("/n");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
if(buffer.toString().trim()!=null){
response.getWriter().print(buffer.toString());
}
}
if(path.equals("/checkcode")){
response.setContentType("image/jpeg");
Map<String, BufferedImage> map = CheckCodeImageUtil.creatCheckImage();
String key = (String)map.keySet().iterator().next();
request.getSession().setAttribute("code",key);
System.out.println("checkcode = " + request.getSession().getAttribute("code"));
BufferedImage image = map.get(key);
ImageIO.write(image, "jpeg", response.getOutputStream());
}
}
}