Ajax Asynchronous interaction and Ajax Asynchronous interaction

Source: Internet
Author: User

Ajax Asynchronous interaction and Ajax Asynchronous interaction

1. What is ajax?
* Asynchronous javascript and xml: asynchronous js and xml
* It can use js to access the server and is asynchronous!
* The response from the server to the client is generally the entire page, an html complete page! However, in ajax, the server does not need to respond to the entire page because it is a partial refresh! It's just data!
> Text: plain text
> Xml: everyone is familiar with it !!!
> Json: it is the data interaction format provided by js. It is the most popular in ajax!

2. Asynchronous interaction and synchronous Interaction
* Synchronization:
> To send a request, you must wait until the server's response ends before sending the second request! In the middle of this period, it is a word "card"
> The page is refreshed!
* Asynchronous:
> After sending a request, you can send a second request without waiting for the response from the server!
> You can use js to receive server responses and then use js to partially refresh them!

3. ajax application scenarios
* Baidu search box
* When a user is registered (check whether the user name has been registered)

4. Advantages and Disadvantages of ajax
Advantages:
* Asynchronous interaction: enhances the user experience!
* Performance: because the server does not need to respond to the entire page and only needs to respond to some content, the pressure on the server is reduced!

Disadvantages:
* Ajax cannot be used in all scenarios!
* Ajax increases the number of visits to the server without reason, putting pressure on the server!

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

Ajax sends asynchronous requests (four steps)

1. Step 1 (get XMLHttpRequest)
* In fact, ajax only needs to learn one object: XMLHttpRequest. If you have mastered it, you will have mastered ajax !!!
* Get XMLHttpRequest
> Most browsers support var xmlHttp = new XMLHttpRequest ();
> IE6.0: var xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP ");
> IE5.5 earlier versions of IE: var xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");

* Compile a function to create an XMLHttpRequest object.
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 2 (open the connection with the server)
* XmlHttp. open (): used to open a connection to the server. It requires three parameters:
> Request Method: It can be GET or POST.
> Request URL: specify server resources, such as;/day23_1/AServlet
> Whether the request is asynchronous: if it is true, an asynchronous request is sent; otherwise, a synchronous request is sent!
* XmlHttp. open ("GET", "/day23_1/AServlet", true );

3. Step 3 (Send request)
* XmlHttp. send (null): If you do not give it, Some browsers may not be able to send it!
> Parameter: The request body content! For a GET request, null is required.

4. Step 4 ()
* Register the listener onreadystatechange on an event of the xmlHttp object
* XmlHttp objects have five statuses:
> 0 status: the system has just been created and the open () method has not been called;
> 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 to respond, but does not indicate that the response has ended!
> 4 Status: the server response has ended! (Usually we only care about this status !!!)
* Get the status of the xmlHttp object:
> Var state = xmlHttp. readyState; // It may be 0, 1, 2, 3, or 4.
* Get the server response status code
> Var status = xmlHttp. status; // For example, 200, 404, or 500
* Get Server Response content 1
> Var content = xmlHttp. responseText; // get the text format of the server response
> Var content = xmlHttp. responseXML; // get the xml response content of the server's response. It is a Document object!

XmlHttp. onreadystatechange = function () {// this method is called in five statuses of xmlHttp.
If (xmlHttp. readyState = 4 & xmlHttp. status = 200) {// dual judgment: determines whether the status is 4 and whether the status is 200
// Obtain the server response content
Var text = xmlHttp. responseText;
}
};

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

Example 2: Send a POST request (if a request must contain parameters, the POST request is generally used)

* Open: xmlHttp. open ("POST "....);
* Add 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


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

Example 3: Check whether the user is registered in the registry form!

1. Compile the page:
* Ajax3.jsp
> Provide the registry form page
> Add an onblur event listener to the username text box.
> Get the content of the text box and send it to the server in step ajax4 to get the response.
* If the value is 1, "the user name has been registered" is displayed in the text box"
* If the value is 0, nothing is done!

2. Compile Servlet
* ValidateUsernameServlet
> Get the user name parameters passed by the client
> Determine whether it is itcast.
* Yes: return 1
* No: 0 is returned.

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

The response content is xml data.

* Server side:
> Set the Response Header ContentType. The value is text/xml and charset = UTF-8.
* Client:
> Var doc = xmlHttp. responseXML; // The Document Object is obtained!

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

Example 4: The response content is xml data

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

Example 5: provincial/municipal Linkage

1. Page
<Select name = "province">
<Option >== select a province ====</option>
</Select>
<Select name = "city">
<Option >== select a city ====</option>
</Select>

2. ProvinceServlet
* ProvinceServlet: request this Servlet immediately after the page is loaded!
> It needs to load the china. xml file and send the names of all provinces to the client using strings!

3. Page work
* Obtain the string separated by commas (,) to obtain the array.
* Cyclically traverse each string (province name) and use each string to create a <option> element to add it to the <select name = "province"> element.

4. CityServlet
* CityServlet: When you select a time-saving page, send a request!
* Get the province name, load the china. xml file, and query the element objects corresponding to the province !, Convert the element into an xml string and send it to the client.

5. Page work
* Delete all child elements in <select name = "city">, but do not delete them. <option >== select city ==</option>
* Get the server response result: doc !!!
* Obtain all the <city> child elements and traverse them cyclically to obtain the <city> content.
* Use the content of each <city> to create a <option> element and add it to <select name = "city">

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

XStream

1. What is the function?
* JavaBean can be converted to (serialized as) xml.

2. XStream jar package
* Core JAR package: xstream-1.4.7.jar;
* Dependency package: xpp3_min-1.1.4c (XML Pull Parser, a fast XML Parser );

3. Procedure
* XStream xstream = new XStream ();
* String xmlStr = xstream. toXML (javabean );

4. Usage Details
* Alias: modified the element name corresponding to the type.
> Xstream. alias ("china", List. class): name the element generated by the List type china.
> Xstream. alias ("province", Province. class): name the element generated by the Province type
* Attribute used: a member of the default class. The child element of the element is generated! We want the class members to generate the attributes of the element.
> Xstream. useAttributeFor (Province. class, "name"): name the member of the Province class and generate the name attribute of the <province> element.
* Remove the fame of the Collection type: We only need the Collection content, and do not want the Collection to generate an element.
> Xstream. addImplicitCollection (Province. class, "cities"): makes the name of the Province class cities (it is a List type, and its content also generates elements) famous without generating elements.
* Remove the specified class to become famous so that it does not generate xml elements.
> Xstream. omitField (City. class, "description"): The generated xml file does not contain the corresponding elements of the City class named description!

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

JSON

1. What is json?
* It is a data exchange format provided by js!

2. json syntax
* {}: Object!
> Attribute names must be enclosed in double quotation marks! Unable to cite a ticket !!!
> Attribute value:
* Null
* Value
* String
* Array: use [] to enclose
* Boolean values: true and false

3. Apply json
* Var person = {"name": "zhangSan", "age": 18, "sex": "male "};

4. Comparison between json and xml
* Readability: XML wins
* Resolution difficulty: JSON itself is a JS object (for home games), which is much simpler.
* Popularity: XML has been popular for many years, but JSON is more popular in the AJAX field.

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

Json-lib

1. What is it?
* It can convert javabean into a json string

2. jar package
* Omitted

3. Core class
* JSONObject --> Map
> ToString ();
> JSONObject map = JSONObject. fromObject (person): converts an object to a JSONObject object.
* JSONArray --> List
> ToString ()
> JSONArray jsonArray = JSONObject. fromObject (list): converts a list to a JSONArray object.

 

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.