The example I gave is an application when a corporate user registers. When the user registers, it checks whether the user name and corporate name are available. The previous method was to add a button next to it, click "Check", send a request to the server, and then Wait...the server returns information and continue the operation.
If we use AJAX technology to implement the above operations, we do not have to wait for the server to return information. When the user enters the user name or company name, when the input text box loses focus, a request will be automatically sent to the server, and the user will continue to perform the following operations. , there is no need to click "Check" or wait for the server to return information. The check and user operation are asynchronous and can be performed at the same time. When the server information is returned, the returned information will be automatically displayed at the corresponding location on the page without refreshing the page, which is equivalent to a partial refresh effect. Let’s look at the code below.
The complete code of the HTML page is as follows:
The following is a quoted fragment:
1< %@page language="java" contentType="text/html;charset=GBK"%>
2<script language="javascript" type="text/javascript">
3<!--
4/**//**Ajax started by Alpha 2005-12-31*/
5
6 var http = getHTTPObject();
7
8 function handleHttpResponse(){
9 if(http.readyState == 4){
10 if(http.status == 200){
11 var xmlDocument = http.responseXML;
12 if(http.responseText!=""){
13 document.getElementById("showStr").style.display = "";
14 document.getElementById("userName").style.background= "#FF0000";
15 document.getElementById("showStr").innerText = http.responseText;
16 }else{
17 document.getElementById("userName").style.background= "#FFFFFF";
18 document.getElementById("showStr").style.display = "none";
19}
20
twenty one }
22 else{
23 alert("The page you requested is abnormal, which may affect your browsing of the information on this page!");
24 alert(http.status);
25}
26}
27}
28
29 function handleHttpResponse1(){
30 if(http.readyState == 4){
31 if(http.status == 200){
32 var xmlDocument = http.responseXML;
33 if(http.responseText!=""){
34 document.getElementById("comNmStr").style.display = "";
35 document.getElementById("comNm").style.background= "#FF0000";
36 document.getElementById("comNmStr").innerText = http.responseText;
37 }else{
38 document.getElementById("comNm").style.background= "#FFFFFF";
39 document.getElementById("comNmStr").style.display = "none";
40}
41
42 }
43 else{
44 alert("The page you requested is abnormal, which may affect your browsing of the information on this page!");
45 alert(http.status);
46 }
47 }
48 }
49
50 function chkUser(){
51 var url = "/chkUserAndCom";
52 var name = document.getElementById("userName").value;
53 url += ("&userName="+name+"&oprate=chkUser");
54 http.open("GET",url,true);
55 http.onreadystatechange = handleHttpResponse;
56 http.send(null);
57 return;
58 }
59 function chkComNm(){
60 var url = "/chkUserAndCom";
61 var name = document.getElementById("comNm").value;
62 url += ("&comName="+name+"&oprate=chkCom");
63 http.open("GET",url,true);
64 http.onreadystatechange = handleHttpResponse1;
65 http.send(null);
66 return;
67 }
68
69 //This function can create the XMLHttpRequest object we need
70 function getHTTPObject(){
71 var xmlhttp = false;
72 if(window.XMLHttpRequest){
73 xmlhttp = new XMLHttpRequest();
74 if(xmlhttp.overrideMimeType){
75 xmlhttp.overrideMimeType('text/xml');
76 }
77 }
78 else{
79 try{
80 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
81 }catch(e){
82 try{
83 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
84 }catch(E){
85 xmlhttp = false;
86}
87 }
88}
89 return xmlhttp;
90}
91/**//**Ajax ends*/
92
93//Detection form
94function chkpassword()
95{
96 var m=document.form1;
97 if(len(m.password.value) > 20 || len(m.password.value) < 5 || !isStr(m.password.value))
98 {
99 document.getElementById("passwordStr").style.display = "";
100 document.getElementById("password").style.background= "#FF0000";
101 document.getElementById("passwordStr").innerText = "Sorry, the password must be English letters, numbers or underscores, and the length is 5~20!";
102 }
103 else
104 {
105 document.getElementById("password").style.background= "#FFFFFF";
106 document.getElementById("passwordStr").style.display = "none";
107 }
108}
109
110function chkconfirmPassword()
111{
112 var m=document.form1;
113 if (m.password.value != m.confirmPassword.value)
114 {
115 document.getElementById("confirmPasswordStr").style.display = "";
116 document.getElementById("confirmPassword").style.background= "#FF0000";
117 document.getElementById("confirmPasswordStr").innerText = "Sorry, the password is inconsistent with the repeated password!";
118 }
119 else
120 {
121 document.getElementById("confirmPassword").style.background= "#FFFFFF";
122 document.getElementById("confirmPasswordStr").style.display = "none";
123 }
124}
125
126function checkfield()
127{
128 var m=document.form1;
129 if(m.userName.value.length==0)
130 {
131 alert("Sorry, the username must be English letters, numbers or underscores, and the length is 5~20.");
132 m.userName.focus();
133 return false;
134}
135 if(m.password.value.length==0)
136 {
137 alert("Sorry, the password must be English letters, numbers or underscores, and the length is 5~20.");
138 m.password.focus();
139 return false;
140 }
141 if (m.password.value != m.confirmPassword.value)
142 {
143 alert("Sorry, the password is inconsistent with the repeated password!");
144 m.confirmPassword.focus();
145 return false;
146 }
147 if(m.comNm.value.length==0)
148 {
149 alert("Sorry, the company name cannot be empty!!");
150 m.comNm.focus();
151 return false;
152 }
153 m.submit();
154}
155
156//-->
157</script>
158<body topmargin="0">
159<form name="form1" method="post" action="/Control?act=Register">
160<table width="100%">
161 <tr><td align="center"> <H2>Ajax demo program</H1></td></tr>
162 <tr><td align="center"> ------ Enterprise Registration By Alpha</td></tr>
163</table>
164
165<HR>
166 <table width="400" border="0" cellpadding="1" cellspacing="1" align="center" >
167 <tr>
168 <td><font color="red">*</font></td>
169 <td>User account:</td>
170 <td>
171 <input type="text" name="userName" maxlength="20" style="background:#FFFFFF" onBlur="chkUser()" value=""/>
172 <div id="showStr" style="background-color:#FF9900;display:none"></div>
173 </td>
174 </tr>
175 <tr>
176 <td><font color="red">*</font></td>
177 <td>Company name:</td>
178<td>
179 <input type="text" name="comNm" maxlength="100" style="background:#FFFFFF" onBlur="chkComNm()" value=""/>
180 <div id="comNmStr" style="background-color:#FF9900;display:none"></div>
181
182 </td>
183 </tr>
184 <tr>
185 <td><font color="red">*</font></td>
186 <td>User password: </td>
187 <td><input type="password" name="password" maxlength="20" style="background:#FFFFFF" onBlur="chkpassword()"/>
188 <div id="passwordStr" style="background-color:#FF9900;display:none"></div>
189 </td>
190 </tr>
191 <tr>
192 <td><font color="red">*</font></td>
193 <td>Confirm password: </td>
194 <td><input type="password" name="confirmPassword" maxlength="20" style="background:#FFFFFF" onBlur="chkconfirmPassword()"/>
195 <div id="confirmPasswordStr" style="background-color:#FF9900;display:none"></div>
196 </td>
197 </tr>
198 </table>
199
200 <div align="center">
201 <input type="button" name="ok" value=" OK" onclick="checkfield()">
202
203 <input type="reset" name="reset" value="Cancel">
204 </div>
205
206</form>
207</body>
208</html>
Use JavaScript to create the XmlHttpRequest class. After sending an HTTP request to the server, the next step is to decide what needs to be done after receiving the response from the server. This requires telling the HTTP request object which JavaScript function to use to handle the response.
You can set the onreadystatechange attribute of the object to thename of the JavaScript function
to be used, as follows:
Created after onreadystatechange.
We call request.open() - it opens the socket channel with the server, using an HTTP verb (GET or POST) as the first parameter and the data provider's URL as the second parameter. The last parameter of request.open() is set to true - it indicates the asynchronous nature of the request. Note that the request has not been submitted yet. With the call to request.send(), the submission begins - this provides any necessary payload for the POST. When using asynchronous requests, we must use the request.onreadystatechanged property to assign the request's callback function. (If the request is synchronous, we should be able to process the results immediately after calling request.send, but we may also block the user until the request is completed.)
Looking at the data provider URL, url = "/chkUserAndCom" , the servlet is as follows:
The following is a reference fragment:
1/**//*
2 * Created on 2005-12-31
3*
4 * TODO To change the template for this generated file go to
5 * Window - Preferences - Java - Code Style - Code Templates
6*/
7package com.event;
8
9import javax.servlet.ServletException;
10import javax.servlet.http.HttpServletRequest;
11import javax.servlet.http.HttpServletResponse;
12
13import com.beans.EBaseInfo;
14
15/** *//**
16 * @author Alpha 2005-12-31
17*
18 * <P>Ajax Demonstration---Checking the enterprise username and enterprise name during enterprise registration</P>
19*
20 * TODO To change the template for this generated type comment go to
21 * Window - Preferences - Java - Code Style - Code Templates
twenty two */
23public class CheckUserAndComNm {
24 private String msgStr = "";
25 protected void doGet(HttpServletRequest request,HttpServletResponse response)
26 throws ServletException
27 {
28
29 EComBaseInfo info=new EComBaseInfo();
30 String oprate=request.getParameter("oprate")).trim();
31 String userName=request.getParameter("userName");
32 String passWord=request.getParameter("password");
33 String comName=request.getParameter("comName");
34
35 try
36 {
37 if(oprate.equals("chkUser"))
38 {
39 response.setContentType("text/html;charset=GB2312");
40 if(userName.length()<5||userName.length()>20)
41 {
42 msgStr = "Sorry, the username must be letters, numbers or underscores, and the length is 5-20 characters!";
43}
44 else
45 {
46 boolean bTmp=info.findUser(userName); //Check whether the user name exists in the database
47 if(bTmp)
48 msgStr = "Sorry, this username already exists, please change the username to register!";
49 else
50 msgStr ="";
51 }
52 response.getWriter().write(msgStr);
53}
54 else if(oprate.equals("chkCom"))
55 {
56 response.setContentType("text/html;charset=GB2312");
57 if(comName.length()<6||comName.length()>100)
58 {
59 msgStr = "Sorry, the company name is 6-100 characters long (excluding spaces within the characters)!";
60 }
61 else
62 {
63 boolean bTmp=info.findCom(comName); //Check whether the company name exists in the database
64 if(bTmp)
65 msgStr = "Sorry, this company name already exists, please change the company name to register!";
66 else
67 msgStr ="";
68 }
69 response.getWriter().write(msgStr);
70
71 }
72 }
73 catch(Exception ex)
74 {
75 }
76 finally
77 {
78 request.setAttribute("url",url);
79 }
80}
81
82 protected void doPost(HttpServletRequest request,HttpServletResponse response)
83 throws ServletException
84 {
85 doGet(request,response);
86}
87}
88
AJAX Technology Summary
1. AJAX (Asynchronous JavaScript and Xml) is a programming technology that combines Java technology, Xml, and JavaScript. It allows you to build Web applications based on Java technology and breaks the convention of using page reloading.
2. AJAX, Asynchronous JavaScript and Xml, is a Web application development method that uses client-side scripts to exchange data with the Web server. In this way, the Web page can be dynamically updated without interrupting the interaction process and re-editing it. Using AJAX, you can create a direct, highly available, richer, and more dynamic Web user interface that is close to native desktop applications.
3. For Mozilla.Netscape, Safari, Firefox and other browsers, the method to create XmlHttpRequest is as follows:
Xmlhttp_request=
new XmlHttpRequest();
4. IE and other browsers to create XmlHttpRequest as follows:
ActiveXObject("Microsoft.XmlHTTP");
5. Xmlhttp_request.open('GET', URL, true); Xmlhttp_request.send(null);
6. The first parameter of open() is the HTTP request method - GET, POST or Whichever method your server supports. According to the HTTP specification, this parameter is capitalized; otherwise, some browsers (such as Firefox) may not be able to handle the request. The second parameter is the URL of the requested page. The third parameter sets whether the request is in asynchronous mode. If TRUE, the JavaScript function will continue execution without waiting for a response from the server. This is the "A" in "AJAX".
If AJAX technology is used well, it will add many friendly effects to our web pages and give users a better feeling. AJAX is a good thing.