Getting started with Ajax instances

Source: Internet
Author: User

I. Open Doors

The blind man can see these times, and AJAX is coming to us. Whether we support or disagree, or turn a blind eye, AJAX is like a wave of trends, turning all of us.

The definition of AJAX is also good. Some people have posted a rich article on the internet, and I don't want to follow this article here.

I just want to talk about some of the advantages I feel. If not, you can also discuss with me:

The first is Asynchronous interaction. The user does not feel the Page Submission and does not wait for the page to return. This is the first experience that users feel when using AJAX pages.

The second is fast response, which is also a strong user experience.

Then we are related to our developers. The successful processing of complex UIS has always worried that the UI in B/S mode is not as rich as the UI in C/S mode. Now, due to the extensive use of JS in AJAX, the complex UI design has become more successful.

Finally, the returned objects of AJAX requests are XML files, which is also a trend, that is, the web service trend. It is easy to combine with WEB Services.

Okay. Let's move on to the subject.

The first example is a web application based on Servlet.

  Ii. servlet-based Ajax

This is a common UI. When you select ZHEJIANG in the first selection box, ZHEJIANG city appears in the second selection box. When you select JIANGSU in the first selection box, the second option box shows the city of JIANGSU.

First, let's look at the configuration file web. xml and configure a servlet in it, as usual:

<Web-app version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>

<Servlet>
<Servlet-name> SelectCityServlet </servlet-name>
<Servlet-class> com. stephen. servlet. SelectCityServlet </servlet-class>
</Servlet>

<Servlet-mapping>
<Servlet-name> SelectCityServlet </servlet-name>
<Url-pattern>/servlet/SelectCityServlet </url-pattern>
</Servlet-mapping>

</Web-app>

Then, let's look at our JSP file:

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> MyHtml.html </title>

<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "this is my page">

<! -- <Link rel = "stylesheet" type = "text/css" href = "./styles.css"> -->

</Head>
<Script type = "text/javascript">
Function getResult (stateVal ){
Var url = "servlet/SelectCityServlet? State = "+ stateVal;
If (window. XMLHttpRequest ){
Req = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
Req = new ActiveXObject ("Microsoft. XMLHTTP ");
}
If (req ){
Req. open ("GET", url, true );
Req. onreadystatechange = complete;
Req. send (null );
}
}
Function complete (){
If (req. readyState = 4 ){
If (req. status = 200 ){
Var city = req. responseXML. getElementsByTagName ("city ");
File: // alert (city. length );
Var str = new Array ();
For (var I = 0; I <city. length; I ++ ){
Str [I] = city [I]. firstChild. data;
}
File: // alert (document. getElementById ("city "));
BuildSelect (str, document. getElementById ("city "));
}
}
}
Function buildSelect (str, sel ){
Sel. options. length = 0;
For (var I = 0; I <str. length; I ++ ){
Sel. options [sel. options. length] = new Option (str [I], str [I])
}
}
</Script>
<Body>
<Select name = "state" onChange = "getResult (this. value)">
<Option value = ""> Select </option>
<Option value = "zj"> ZEHJIANG </option>
<Option value = "zs"> JIANGSU </option>
</Select>
<Select id = "city">
<Option value = "/blog/"> CITY </option>
</Select>
</Body>
</Html>

At first glance, it seems like our common JSP. Take a closer look at the differences in JS.

First, let's look at the first method: getResult (stateVal). In this method, first we get XmlHttpRequest; then we set the request url: req. open ("GET", url, true); then set the Receiving Method of the request return value: req. onreadystatechange = complete; the method for receiving the returned value is -- complete (); the last is to send the request: req. send (null );

Then let's take a look at our method for receiving the returned value: complete (). In this method, we first determine whether the returned value is correct. If the returned value is correct, we use DOM to parse the returned XML file. The usage of DOM is not described here. Please refer to the relevant documents. After obtaining the value of city, you can use the buildSelect (str, sel) method to assign values to the corresponding selection box.

Finally, let's take a look at the Servlet File:

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;

/**
* @ Author Administrator
*
* TODO To change the template for this generated type comment go
* Window-Preferences-Java-Code Style-Code Templates
*/
Public class SelectCityServlet extends HttpServlet {

Public SelectCityServlet (){
Super ();
}

Public void destroy (){
Super. destroy ();
}

Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("text/xml ");
Response. setHeader ("Cache-Control", "no-cache ");
String state = request. getParameter ("state ");
StringBuffer sb = new StringBuffer ("<state> ");
If ("zj". equals (state )){
Sb. append ("<city> hangzhou </city> <city> huzhou </city> ");
} Else if ("zs". equals (state )){
Sb. append ("<city> nanjing </city> <city> yangzhou </city> <city> suzhou </city> ");
}
Sb. append ("</state> ");
PrintWriter out = response. getWriter ();
Out. write (sb. toString ());
Out. close ();
}
}

This class is also very simple. First, get the state parameter from the request, then generate the corresponding XML file based on the state parameter, and finally output the XML file to the PrintWriter object.

So far, the code in the first example has all ended. Is it relatively simple? Let's go to the second instance! This is an AJAX Application Based on JSP.

  Iii. jsp-based Ajax

This example is about Input Validation. We know that when applying for a user, you must go to the database to confirm the uniqueness of the user before continuing to apply.

This verification requires access to the back-end database, but does not require users to wait after submitting it here. Of course, it is time for AJAX technology to show its strength.

First, let's look at the JSP that displays the UI:

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> check.html </title>

<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "Description" content = "this is my page">

<! -- <LINK rel = "stylesheet" type = "text/CSS" href = "./styles.css"> -->

</Head>
<SCRIPT type = "text/JavaScript">
VaR http_request = false;
Function send_request (URL) {// initialize, specify the processing function, and send the request Function
Http_request = false;
File: // start initializing the XMLHTTPRequest object
If (window. XMLHttpRequest) {file: // Mozilla Browser
Http_request = new XMLHttpRequest ();
If (http_request.overridemimetype) {// sets the mime category
Http_request.overridemimetype ('text/xml ');
}
}
Else if (window. activexobject) {// IE browser
Try {
Http_request = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
Http_request = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){}
}
}
If (! Http_request) {// exception. An error occurred while creating the object instance.
Window. alert ("the XMLHttpRequest object instance cannot be created .");
Return false;
}
Http_request.onreadystatechange = processRequest;
// Determine the request sending method and URL and whether to execute the following code synchronously
Http_request.open ("GET", url, true );
Http_request.send (null );
}
// Function for processing the returned information
Function processRequest (){
If (http_request.readyState = 4) {// judge the object status
If (http_request.status = 200) {// The information has been returned successfully. Start to process the information.
Alert (http_request.responseText );
} Else {file: // The page is abnormal.
Alert ("the page you requested has an exception. ");
}
}
}
Function userCheck (){
Var f = document. form1;
Var username = f. username. value;
If (username = ""){
Window. alert ("The user name can not be null! ");
F. username. focus ();
Return false;
}
Else {
Send_request ('check1. jsp? Username = '+ username );
}
}

</Script>
<Body>
<Form name = "form1" action = "" method = "post">
User Name: <input type = "text" name = "username" value = "> & nbsp;
<Input type = "button" name = "check" value = "check"Onclick= "UserCheck ()">
<Input type = "submit" name = "submit" value = "submit">
</Form>
</Body>
</Html>

All JS files are the same as the previous example. The difference is that they only operate on the returned values. This time, alert is used to display: Alert (http_request.responsetext );

Let's look at the processing logic JSP:

<% @ Page contenttype = "text/html; charset = gb2312" Language = "Java" errorpage = "" %>
<%
String username = request. getparameter ("username ");
If ("educhina". Equals (username) Out. Print ("the user name has been registered. Please change to another user name. ");
Else Out. Print ("the user name has not been used. You can continue. ");
%>

It is very simple. first obtain the parameter, then process it, and finally print the result in the out.
In our third example, we still use this uniqueness verification as an example. This time we combined the struts development framework to complete Ajax development.

  4. Struts-based Ajax

First, we will still configure the struts application, or in the Struts-config and XML files, as shown below:

<Action type = "com. Ajax. checkaction"
Scope = "request" Path = "/ajax/check">
<Forward name = "success" Path = "/check. jsp"/>
</Action>

The configuration is the same as that of a common Struts application, but there is no ActionForm configuration.

The following is the Action class:

Package com. ajax;

Import java. io. PrintWriter;

Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;

Import org. apache. struts. action. Action;
Import org. apache. struts. action. ActionForm;
Import org. apache. struts. action. ActionForward;
Import org. apache. struts. action. ActionMapping;
Import org. apache. struts. action. DynaActionForm;

/**
* @ Author Administrator
*
* TODO To change the template for this generated type comment go
* Window-Preferences-Java-Code Style-Code Templates
*/
Public class CheckAction extends Action
{
Public final ActionForward execute (ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
Throws Exception
{
System. out. println ("haha ............................... ");
String username = request. getParameter ("username ");
System. out. println (username );
String retn;
If ("educhina". equals (username) retn = "Can't use the same name with the old use, pls select a difference ...";
Else retn = "congraducation! You can use this name ....";
PrintWriter out = response. getWriter ();
Out. write (retn );
Out. close ();
Return mapping. findForward ("success ");
}
Public static void main (String [] args)
{
}
}

We can see that the logic inside is the same as the logic in Servlet in the example. Finally, let's take a look at JSP:

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> Check.html </title>

<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "this is my page">

<! -- <Link rel = "stylesheet" type = "text/css" href = "./styles.css"> -->

</Head>
<Script type = "text/javascript">
Var http_request = false;
Function send_request (url) {// initialize, specify the processing function, and send the request function
Http_request = false;
File: // start initializing the XMLHttpRequest object
If (window. XMLHttpRequest) {file: // Mozilla Browser
Http_request = new XMLHttpRequest ();
If (http_request.overrideMimeType) {// sets the MiME category
Http_request.overrideMimeType ('text/xml ');
}
}
Else if (window. ActiveXObject) {// IE browser
Try {
Http_request = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
Http_request = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){}
}
}
If (! Http_request) {// exception. An error occurred while creating the object instance.
Window. alert ("the XMLHttpRequest object instance cannot be created .");
Return false;
}
Http_request.onreadystatechange = processRequest;
// Determine the request sending method and URL and whether to execute the following code synchronously
Http_request.open ("GET", url, true );
Http_request.send (null );
}
// Function for processing the returned information
Function processRequest (){
If (http_request.readystate = 4) {// judge the object status
If (http_request.status = 200) {// The information has been returned successfully. Start to process the information.
Alert (http_request.responsetext );
} Else {file: // The page is abnormal.
Alert ("the page you requested has an exception. ");
}
}
}
Function usercheck (){
VaR F = Document. Forms [0];
VaR username = f. username. value;
If (username = ""){
Window. Alert ("the user name can not be null! ");
F. username. Focus ();
Return false;
}
Else {
Send_request ('ajax/check. do? Username = '+ username );
}
}

</SCRIPT>
<Body>
<Form name = "form1" Action = "" method = "Post">
User name: <input type = "text" name = "username" value = "> & nbsp;
<Input type = "button" name = "check" value = "check"Onclick= "Usercheck ()">
<Input type = "Submit" name = "Submit" value = "/blog/submit">
</Form>
</Body>
</Html>

We can see that JSP is basically the same, except for the URL to be sent: ajax/check. do? Username = "+ username.

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.