Ajax Asynchronous Interaction Basics

Source: Internet
Author: User

1. What is Ajax?
* Asynchronous JavaScript and XML: Asynchronous JS and XML
* It can use JS to access the server, but also asynchronous access!
* The response of the server to the client is generally the entire page, an HTML full page! But in Ajax because it is a partial refresh, then the server will no longer respond to the entire page! And just data!
> Text: Plain text
> xml: Everyone is familiar with!!!
> JSON: It is the data interaction format provided by JS, which is most popular in Ajax!

2. Asynchronous interaction and synchronous interaction
Synchronization
> Send a request, wait for the server's response to end before sending a second request! The middle of the time is a word "card"
> Refresh is the entire page!
Asynchronous
> After sending a request, you don't have to wait for the server to respond, and then you can send a second request!
> can use JS to receive the response of the server, and then use JS to local refresh!

3. Ajax Application Scenarios
* Baidu's search box
* When the user registers (verify that the user name has been registered)

4. Advantages and disadvantages of Ajax
Advantages:
* Asynchronous Interaction: Enhances the user's experience!
* Performance: Because the server does not need to respond to the entire page, only need to respond to partial content, so the server pressure is reduced!

Disadvantages:
* Ajax cannot be applied in all scenarios!
* Ajax has increased the number of accesses to the server, causing pressure on the server!

==========================================
==========================================

Ajax sends asynchronous requests (four-step operation)

1. First step (get XMLHttpRequest)
* Ajax actually only need to learn an object: XMLHttpRequest, if mastered it, mastered the ajax!!!
* Get XMLHttpRequest
> Most browsers support: var xmlHttp = new XMLHttpRequest ();
> Ie6.0:var xmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
> IE5.5 with an earlier version of Ie:var xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");

* Writing functions to create XMLHttpRequest objects
function Createxmlhttprequest () {
try {
return new XMLHttpRequest ();
} catch (e) {
try {
return new ActiveXObject ("Msxml2.xmlhttp");
} catch (e) {
try {
return new ActiveXObject ("Microsoft.XMLHTTP");
} catch (e) {
Alert ("Dude, what browser are you using?") ");
Throw e;
}
}
}
}

2. Step two (open the connection to the server)
* Xmlhttp.open (): Used to open a connection to the server, it requires three parameters:
> Request method: Can be get or post
> URL of the request: Specify server-side resources, for example;/day23_1/aservlet
> Whether the request is asynchronous: If true means sending an asynchronous request, otherwise synchronizing the request!
* Xmlhttp.open ("GET", "/day23_1/aservlet", true);

3. Step three (send request)
* Xmlhttp.send (NULL): If not given may cause some browsers to fail to send!
> Parameters: Is the request body content! If it is a GET request, NULL must be given.

4. Step Fourth ()
* Register listener on an event of the XMLHTTP object: onreadystatechange
* There are 5 states for XMLHTTP objects:
> 0 Status: Just created, not yet called the Open () method;
> 1 Status: Request Start: The open () method is called, but the Send () method has not been called
> 2 Status: The Send () method has been called;
> 3 Status: The server has started responding, but does not indicate that the response is over!
> 4 Status: Server Response end! (usually we only care about this state!!!) )
* Get the status of the XMLHTTP object:
> var state = xmlhttp.readystate;//may be 0, 1, 2, 3, 4
* Get status code for server response
> var status = xmlhttp.status;//For example 200, 404, 500
* Get the contents of the server response 1
> var content = xmlhttp.responsetext;//The contents of the text format to get the response from the server
> var content = xmlhttp.responsexml;//Gets the contents of the response XML response of the server, it is the Document Object!

Xmlhttp.onreadystatechange = function () {//xmlhttp 5 states will call this method
if (xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {//Double judgment: Determine whether it is a 4 state, and also to determine whether it is 200
Get the response content of the server
var text = Xmlhttp.responsetext;
}
};

==========================================
==========================================

Second example: Send a POST request (usually with a POST request if you need to send a request with parameters)

* Open:xmlHttp.open ("POST" ...);
* Add a step: Set the Content-type request header:
> Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
* Send:xmlHttp.send ("username=zhangsan&password=123");//Specify the request body when sending a request


==========================================
==========================================

The third example: Check the registration form of the user is registered!

1. Write the page:
* ajax3.jsp
> Give a Registration Form page
> Add a onblur Event listener to the User name text box
> Get the contents of the text box and send it to the server via AJAX4 to get the response result
* If 1: "User name has been registered" after text box
* If it is 0: do nothing!

2. Writing a servlet
* Validateusernameservlet
> Get the user name parameters passed by the client
> Determine if it is itcast
* Yes: return 1
* No: return 0

==========================================
==========================================

Response content is XML data

* Server side:
> Set the response header: ContentType, whose value is: Text/xml;charset=utf-8
Client
> var doc = xmlhttp.responsexml;//Gets the Document Object!

=====================

Fourth example: Response content is XML data

==========================================
==========================================

Fifth example: Provincial and municipal linkage

1. Page
<select name= "Province" >
<option>=== Please select the province ===</option>
</select>
<select name= "City" >
<option>=== Please select City ===</option>
</select>

2. Provinceservlet
* Provinceservlet: When the page is finished loading, request this servlet! immediately.
> It needs to load the China.xml file and send all the province names using strings to the client!

3. The work of the page
* Get this string, separated by commas, to get the array
* Loop through each string (the name of the province), create a <option> element with each string to add to <select name= "province" > this element

4. Cityservlet
* Cityservlet: When the page selects a province, send the request!
* Get the name of the province, load the China.xml file, query the corresponding element object in the province! , convert this element into an XML string, and send it to the client

5. The work of the page
* Remove all child elements from the <select name= "City" >, but do not delete <option>=== Please select cities ===</option>
* Get the server response result: doc!!!
* Get all <city> sub elements, loop through, get <city> content
* Create a <option> element with each <city> content, add to <select name= "City" >

==========================================
==========================================

XStream

1. What role
* JavaBean can be converted to (serialized) XML

2. XStream Jar Package
* Core jar package: Xstream-1.4.7.jar;
* Must depend on package: xpp3_min-1.1.4c (XML Pull Parser, a fast XML parser);

3. Steps to use
* XStream XStream = new XStream ();
* String xmlstr = xstream.toxml (JavaBean);

4. Usage details
* Alias: Modify the element name corresponding to the type
> Xstream.alias ("China", List.class): Let the List type generate an element named China
> Xstream.alias ("Province", Province.class): Let the province type generate an element named province
* Use as attribute: the member of the default class, the child element of the element is generated! We want members of the class to generate the attributes of the element
> xstream.useattributefor (province.class, "name"): Province class named name member, build <province> element's Name property
* Remove collection type of fame: we only need to collection the content, and do not want collection itself to generate an element
> xstream.addimplicitcollection (Province.class, "Cities"): Make the name of the province class cities (it is a list type, its contents will also generate elements) of fame does not generate elements
* Remove the specified fame from the class so that it does not generate XML elements
> Xstream.omitfield (city.class, "description"): the corresponding element named description in the City class will not appear in the generated XML!

==========================================
==========================================

Json

1. What is JSON
* It is a data interchange format provided by JS!

2. The syntax of JSON
* {}: is an Object!
> attribute names must be enclosed in double quotes! Single citation not!!!
> Attribute values:
* NULL
* Value
* String
* Arrays: Using [] Surround
* Boolean value: True and False

3. Apply JSON
* var person = {' name ': ' Zhangsan ', ' age ': ' Sex ': ' Male '};

4. JSON and XML comparison
* Readability: XML wins
* Parsing difficulty: JSON itself is the JS object (home combat), so much simpler
* Popularity: XML has been popular for many years, but in the Ajax world, JSON is more popular.

-----------------------------------

Json-lib

1. What is it?
* It can convert JavaBean into JSON string

2. Jar Package
* Slightly

3. Core class
* Jsonobject Map
> toString ();
> Jsonobject map = jsonobject.fromobject (person): Convert object to Jsonobject object
* Jsonarray-List
> toString ()
> Jsonarray Jsonarray = jsonobject.fromobject (list): Convert list to Jsonarray object

Ajax Asynchronous Interaction Basics

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.