Javaweb Ajax QuickStart (19)

Source: Internet
Author: User


AJAX 1. Introduction to Ajax
1. What is Ajax
The technology that allows browsers to communicate with servers without refreshing the current page is called Ajax. AJAX is not a new programming language, but a combination of multiple technologies to form a new technology
Ajax = DHTML (HTML, CSS, JavaScript) + XMLHttpRequest object
2. Features of Ajax
Not applicable to any application scenario
Leading to logic processing confusion
AJAX is to realize asynchronous interaction in B \ S mode
Ajax performs better with the same functionality
3. The advantages of Ajax
1) In the traditional web interaction model, the browser sends the request directly to the server, the server sends back the response, and sends it directly to the browser, the Ajax interaction model. The browser first sends the request to the Ajax engine (with XMLHttpRequest as the core), the Ajax engine then sends the request to the server, the server sends back the response to the Ajax engine first, and then the engine sends it to the browser for display
2) . purpose to improve user experience
2. Synchronous and asynchronous interactions
Synchronous interaction: the client sends a request to the server - > the server responds. In this process,
A pattern in which clients can't do anything else
Asynchronous interaction: the client sends a request to the server - > the server responds. In this process, the client can do anything else
3. Steps to implement Ajax
1. Create XMLHttpRequest object
2. Bind state trigger to function (callback function)
3. Use the open method to establish the connection with the server
4. Send data to the server
5. Processing the returned data in the callback function
4. Common Object XMLHttpRequest
Method:
Open
Send
Properties:
Onreadystatechange: status callback function
ResponseText / responsexml: response string of the server
Status: HTTP status code returned by the server
Statustext: HTTP status information returned by the server
ReadyState: object state (0,1,2,3,4)
Event:
Onreadystatechange: corresponds to a function. Callback function. Every time the readyState value changes, the function specified by it is called.
---------------------------------------------------------
The readyState property indicates the current state of the Ajax request. Its value is represented by a number.
0 means not initialized. The open method has not been called yet
1 means loading. The open method has been called, but the send method has not yet been called
2 means loading is complete. Send has been called. Request started
3 represents interaction. Server sending response
4 for completion. Response sent
Status common status codes and their meanings:
404 Not Found
403 Forbidden
500 internal service error
200 all right
304 not modified (the server returns 304 status, indicating that the source file has not been modified
5. Client submits data to the server
 
 
Different response data type 1. Introduction to JSON
1. JSON (JavaScript object notation) is a JavaScript lightweight data interaction format, which is mainly used in Ajax programming. Removing redundant HTML tag elements and returning only valid data is a better solution
2. JSON features:
1) . easy for programmers to read and write
2) . easy for computer analysis and generation
3. JSON structure: map collection structure, array structure
4. JSON format:
1) {key: value, key: value, key: value} key value pairs are used directly, separately, between key values: the key itself must be a string constant
2) . [value 1, value 2, value 3] array structure
5. Application scenario: Ajax request parameters and response data
2. Json-lib use
1. JSON lib is a Java class library, which supports the conversion of JSON format strings by JavaBean map list array and the conversion of JSON strings to JavaBean objects
2. guide pack
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
3. How to use JSON Lib
1) . convert array, list collection to JSON format string - use jsonarray
String[] arr = {"sada","fdssd","dfsd","sadas"};
JSONArray jsonArray =  JSONArray.fromObject(arr);
2) . parse JavaBean / map into JSON string: - use jsonobject
JSONObject jsonObject = JSONObject.fromObject(new Person());
3) . configure which properties of the object do not participate in the transformation through the jsonconfig object
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"price"});
JSONObject jsonObject = JSONObject.fromObject(p1, jsonConfig);
3. Other third-party tools: XStream
1. How to convert JavaBean, list, array and map collections into XML format
The third-party class library is required to support xStream, and the packages are xstream-1.3.1.jar, xpp3_min-1.1.4c.jar
Core approach
Xstream.alias (name, class); define an alias by parsing or serializing the type
Toxml (obj) serializes objects into XML
From XML (InputStream / XML fragment) parses XML information into objects
Provide convenient notes
@Xstreamalias alias classes and variables
@Xstreamasattribute set variable generation attribute
@Xstreamimitfield set variable is not generated to XML
@Xstreamimlicit (itemfieldname = "hobbies") set collection type variable alias
Make comments effective
xStream.autodetectAnnotations(true);
Use xmlhttp.responsexml to receive and parse to document object

The Ajax case tool class is used to return a XMLHttpRequest object for the case to get the object
function getXmlHttpRequest() {
Var xmlHttp;
Try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
Try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
Try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
Alert ("your browser does not support Ajax! "";
return false;
}
}
}
return xmlHttp;
}
1. User Registration Tips
Introduce util.js tool to get XMLHttpRequest object easily
1. Page design:
Provide user name input box to set ID and name values
Span locale ID value
2. Load the page, create an Ajax engine, and process the data responded by the server
1) . respond as soon as the window.onload page is loaded
2) First, obtain the node object through the document object of the text input box, and generate the defocus event with the onblur method
3) . get Ajax engine, XMLHttpRequest object
4) . the listening state is bound with a callback function, which uses the onreadystatechange method in the engine object to listen, judge whether the state is the readyState returned by the server (4), and then judge whether the response is successful (200)
5) . if all conditions are met, process the result of the server response
Xmlhttp.responsetext; get general data of response
Xmlhttp.responsexml: get the XML text data of the response
6) . establish the connection and use the open method in the engine
7) . send data, xmlhttp. Send ("");
3. Server response class xmlhttprequestservlet
1) . set code
2) . get requested parameters
3) . process the requested parameters and send the results
2. Display product Information
Introduce util.js tool to get XMLHttpRequest engine
1. Page design
Define a list of hyperlinked products, and set the ID in the href = "javascript: void (0);"
Define div display table area
2. Page loading definition
1) . window.onload load page
2) . get onclick method in hyperlink node object
3) . get XMLHttpRequest object
4) . bind the state to the xmlhttp.onreadystatechange method on the event trigger
5) . process the data responded by the server
6) . establish a connection using the open method
7) . send request information send method
3. response class
Set encoding
Set the product list to the request field
Forward to the product list page list.jsp
4. Product list page design
1) . import JSTL tag library
2) . create the table label, set the title, traverse the objects in the request field, and use the El expression to get the data
3. JSON implementation displays product information
1、 Creating JavaBean classes
private String name;
private double price;
Storage class productdb
List<Product> products = new ArrayList<Product>();
Products. Add (new product ("washing machine", 1000));
Products. Add (new product ("refrigerator", 1500));
Products. Add (new product ("TV", 5000));
2、 Page display
Provide product list link, set the value of the href attribute javascript: void (0);, set the ID
Div display area
3、 Ajax engine writing
0. Introduce tool tag to get XMLHttpRequest object
1. Execute the page loading method window.onload
2. get the Ajax engine object
3. Bind the returned state to the event trigger method
4. Judge whether the current status of the Ajax request has responded (4), and then judge whether the response status code has responded successfully (200)
5. Get the result of the server response. Because it is a JSON object, you can use the eval function to generate the corresponding object
6. Create tables and set attribute values
7. Traverse the JSON object, insert the row and cell in the table, and set the value in the cell
8. Finally, add the table to the div area
9. Establish connection and send
4、 Write server servlet class
1. Create jsontableservlet class
2. Set output code
3. Get product data and encapsulate it into JSON object
4. Output JSON object
4. XStream package provincial name to achieve level two linkage
1、 Establish city / Province
Class City
private String name;
private String description;
Class Province
private String name;
private String prefix;
private List<City> cities = new ArrayList<City>();
Provincedb class
private List<Province> ps = new ArrayList<Province>();
Province SD = new province ("Shandong Province", "SD");
SD. Getcities(). Add (New City ("Jinan City", "provincial capital");
SD. Getcities(). Add (New City ("Qingdao city", "coastal city");
SD. Getcities(). Add (New City ("Zibo City", "heavy industry");
Province HB = new province ("Hubei Province", "HB");
Hb. Getcities(). Add (New City ("Wuhan City", "provincial capital");
Hb. Getcities(). Add (New City ("Huanggang City", "good teaching");
Hb. Getcities(). Add (New City ("Jingzhou City", "three ancient cities");
Ps.add (SD);
Ps.add (HB);
2、 Set up servlet class of server response
1. Set output code
2. New an xStream for generating XML objects
3. Enable automatic detection annotation
4. Convert objects to XML
5. Output objects
3、 Page design
Province and city options drop-down menu, where province sets onchange event
4、 Write Ajax engine
1. Select province drop-down menu
1) . import util.js
2) . page loading method window.onload
3) . get the Ajax engine, and the binding status returns the listening event method xhr.onreadystatechange method
4) . judge whether the current state has responded (4). Judge whether the response is successful, status code (200)
5) . get the object responsexml of the XML response
6) . get the province drop-down menu node object
7) . get the province node from the response object and get a set of province values
8) . traversing the provincearr node object
9) . read the value of the name attribute of each node
10) . generate the option object and assign the read value
11) . add the option object to the province node
2. Select province change city list (province selection triggers onchange event)
1) . get province drop-down list node object
2) . get the value provincesel.options [provincesel. Selectindex]. Text of the province drop-down list object
3) . get the city drop-down list node object
4) . get all nodes of the province through the XML object responded by the server
5) . judge whether the value of the province object is equal to the initial value,
6) . if it is equal, create a new option object, assign the initial value of the option, clear the original node of the city, and add the opt to the city list
7) . otherwise, execute cloth 6 first (do not need initial value, see whether to execute cloth 6)
8) . traversing node objects of provinces
9) . get the value of province attribute
10) . judge whether the selected value is equal to the value of the responding Province
11) . if this province is found, get all child nodes by responding to the node object of the province
12) . traverse the child node object (that is, the nodes of all cities)
13) . first, judge whether it is a node object. Through nodeType = = 1
14) . get the value of every city node
15) . create a new option object and assign the value of the city node to it
16) . finally, add the option to the city 


Javaweb Ajax QuickStart (19)


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.