Writing user registration Examples and technical summary with Ajax

Source: Internet
Author: User
Tags object html page http request reset return string window
ajax | User registration The example I cited is an application when a business user is registered. When the user is registered, check whether the user name and business name are available. The previous method was to add a button next to it and click "check" to the server Make a request and wait ... the server returns a message and continues. If we use Ajax technology to achieve the above operations, we do not have to wait for the server to return information. When the user enters the user name or the company name, when the input text box loses focus, it will automatically make a request to the server, and the user continues to do the following You don't need to click "Check" or wait for the server to return information. The check is asynchronous to the user operation and can be performed at the same time. When the server information is returned, the returned information will be automatically displayed at the corresponding position on the page. It is not necessary to refresh the page, which is equivalent to the effect of partial refresh.

Let's look at the code.

完整 The complete code of the HTML page is as follows:

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 the information you browse to 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 ("An exception occurred on the page you requested, which may affect your browsing information!");
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, 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 does not match the duplicate password!";
118}
119 else
120 {
121 document.getElementById ("confirmPassword"). Style.background = "#FFFFFF";
122 document.getElementById ("confirmPasswordStr"). Style.display = "none";
123}
124}
125
126 function checkfield ()
127 {
128 var m = document.form1;
129 if (m.userName.value.length == 0)
130 {
131 alert ("Sorry, the user name must be English letters, numbers or underscores, 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, 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 does not match the duplicate 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" > ------ Company 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" >
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 needs to tell the HTTP request object which JavaScript function to use to process the response. You can set the object's onreadystatechange property to the function name of the JavaScript to be used, as follows: xmlhttp_request.onreadystatechange = FunctionName;

FunctionName is the name of the function created in JavaScript. Be careful not to write FunctionName (). Of course, we can also create JavaScript code directly 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 URL of the data provider 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. With the call to request.send (), the commit begins-this can provide any necessary payload for POST. When using asynchronous requests, we must use the request.onreadystatechanged property to allocate the callback function for the request. (If the request is synchronous, we should be able to process the result immediately after calling request.send, but we may also block the user until the request is completed.)

Look at the URL of the data provider, url = "/ chkUserAndCom", the servlet is as follows:


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 demo --- check company user name and company name during company registration
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); // Find out if the user name exists in the database
47 if (bTmp)
48 msgStr = "Sorry, this username already exists, please change your 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 characters)!";
60}
61 else
62 {
63 boolean bTmp = info.findCom (comName); // Find out if the company name is in the database
64 if (bTmp)
65 msgStr = "Sorry, this company name already exists, please change the company name registration!";
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 combining 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 script to exchange data with a web server. In this way, the Web page can be dynamically updated without interrupting the interactive process and re-cutting. With Ajax, you can create direct, highly available, richer, more dynamic Web user interface interfaces that are close to native desktop applications.

3. For browsers such as Mozilla, Netscape, Safari, and Firefox, the XMLHttpRequest method is created as follows:

xmlhttp_request = new XMLHttpRequest ();

4. The methods of creating XMLHttpRequest such as IE are as follows:

Xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP")

Or xmlhttp = new 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 whatever method you want to be supported by the server. According to the HTTP specification, this parameter must be capitalized; otherwise, some browsers (such as Firefox) may not be able to process 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 to execute without waiting for a response from the server. This is the "A" in "AJAX".
The good use of Ajax technology adds a lot of friendly effects to our web pages and gives users a better feeling. Ajax is a good thing.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.