Ajax learning Note 1 in jquery

Source: Internet
Author: User

AJAX introduction:
AJAX refers to Asynchronous JavaScript And XML (Asynchronous JavaScript And XML), And is a web development technology used to create interactive web applications. Through AJAX, JavaScript can use the XMLHttpRequest object of JavaScript to directly communicate with the server. With this object, JavaScript can exchange data with the Web server without reloading the page.
JQuery is a javascript framework and a lightweight encapsulation of javascript, which is easy to understand.
Ajax is an asynchronous request technology that combines xml and javascript to achieve dynamic refresh.
Ajax preparation:
1. Download jquery:
Official site of the latest: http://blog.jquery.com/2011/09/01/jquery-1-6-3-released/
When downloading, right-click jQuery 1.6.3 Minified or jQuery 1.6.3 Uncompressed and choose "use thunder download"
2. Overview
2.1.ajax asynchronous transmission steps:
1. Use dom to get the attribute values in the text box
Document. getElementById ("id name"). value
2. Create an XMLHttpRequest object
XMLHttpRequest and ActiveXObject are available based on different browsers.
3. register the callback function. When registering the callback function, you only need the function name. Do not add brackets.
When the callback function is registered, the data returned by the server is obtained:
Method 1: Obtain plain text data output by the server
Method 2: Use responseXML to accept DOM objects of XML Data Objects
4. Set connection information
5. Send data and start interaction with the server.
Post/get

2.2.ajax methods:
(1). getElementById ("id attribute value "):
Obtains an object based on the specified id property value.
(2). getElementsByTagName (tagname ):
Returns a set of elements with the specified name by searching for any HTML element in the entire HTML document.
(3). selector:
Selectors include basic selectors, hierarchical selectors, and attribute selectors. This program only has the basic selector # id, such:
$ ("# MyDiv"): Find the element whose ID is "myDiv"
2.3.XMLHttpRequest object:
XMLHttpRequest allows you to update a webpage without reloading the page. After the page is loaded, the client requests data from the server and receives data from the server after the page is loaded, send data to the client in the background.
2.3.1. Method:
(1) overrideMimeType ("text/html "):
Overwrite the header sent to the server and force text/xml as the mime-type
(2) open (method, url, async, username, password ):
Initialize HTTP request parameters, such as URLs and HTTP methods, but do not send requests.
The method parameter is the HTTP method Used for the request, including GET, POST, and HEAD;
The url parameter is the request body.
The async parameter indicates whether the request is synchronous or asynchronous, and the false request is synchronous, and the true request is asynchronous.
The username and password parameters are optional and provide authentication qualifications for url Authorization. If they are specified, they will overwrite any qualifications specified by the url itself.
(3) send (body ):
Sends an HTTP request, uses parameters passed to the open () method, and optional request bodies passed to the method.
Send (body) if the HTTP method specified by calling open () is POST or PUT, the body parameter specifies the Request body as a string or Document object. If the request body is not required, this parameter is null.
If the previously called open () parameter async is false, this method will be blocked and will not be returned until the readyState is 4 and the server's response is fully received.
If the async parameter is true, or this parameter is omitted, send () returns immediately, and as described later, the server response will be processed in a background thread.
(4) setRequestHeader (name, value ):
Set or add an HTTP request to an opened but not sent request
The name parameter is the name of the header to be set. This parameter should not contain white spaces, colons, or line breaks.
The value parameter is the value of the header. This parameter should not contain line breaks
2.3.2. attributes:
(1) onreadystatechange:
The event handle function called every time the readyState attribute is changed. When readyState is 3, it may also be called multiple times.
(2) readyState:
HTTP Request status. When an XMLHttpRequest is created for the first time, the value of this attribute starts from 0 until the complete HTTP response is received. This value is increased to 4.
Each of the five States has an associated informal name. The following table lists the status, name, and meaning:

The value of readyState will not decrease unless a request calls the abort () or open () method during processing. The onreadystatechange event handle is triggered every time the value of this attribute is increased.
(3) status:
The HTTP status code returned by the server. For example, 200 indicates success, and 404 indicates "Not Found" error. When readyState is less than 3, reading this attribute will cause an exception.
(4) responseText:
The response body received from the server (excluding the header) So far, or if no data is received, it is a null string.
If readyState is less than 3, this attribute is an empty string. When readyState is 3, this attribute returns the response that has been received. If readyState is 4, this attribute stores the complete response body.
If the response contains a header that specifies the character encoding for the response body, this encoding is used. Otherwise, assume that the Unicode UTF-8 is used
(5) responseXML: the response to the request, which is parsed as XML and returned as a Document Object

Sample Code:
Note: This example consists of the front-end and back-end. The back-end adopts servlet implementation, but does not go to the database for data verification. The front-end is composed of html and javascript. The front-end verification adopts two methods: jquery-encapsulated ajax for dynamic form verification, and XMLHttpRequest object for dynamic form verification, the difference between the two verification methods is that javascript scripts are different, and the front-end pages and backend servlets are the same.

Frontend ajax.html

Copy codeThe Code is as follows: <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"
Http://www.w3.org/TR/html4/loose.dtd>
<Html>
<Head>
<Title> ajax </title>
<! -- Import js, pay attention to the src path -->
<Script type = "text/javascript" src = "jslib/jquery. js"> </script>
<Script type = "text/javascript" src = "jslib/verify. js"> </script>
</Head>
<Body>
<! -- Ajax does not need to submit data in forms, so it does not need to write form tags -->
<! -- Ajax does not need the name attribute and requires an id attribute -->
<! -- The onblur event occurs when the object loses focus -->
Username: <input type = "text" id = "username" onblur = "verify3 ()"/> <div id = "result"> </div>
</Br>
<Input type = "submit" value = "login" onclick = "login ()"/>
</Body>
</Html>

Background AJAXServer. java:Copy codeThe Code is as follows: import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import javax. servlet. ServletException;
Import java. io. IOException;
Import java. io. PrintWriter;
Public class AJAXServer extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("text/html; charset = UTF-8 ");
PrintWriter out = response. getWriter ();
// 1. Take the Parameter
String old = request. getParameter ("name ");
// 2. Check for any problems
If (old = null | old. length () = 0 ){
Out. println ("the user name cannot be blank ");
} Else {
// 3. Verify the operation
String name = old;
If (name. equals ("pan ")){
// 4. Different from traditional applications. In this step, you need to return the data you are interested in to the page, instead of to the new page.
Out. println ("user name [" + name + "] already exists ");
} Else {
Out. println ("user name [" + name + "] available ");
}
}
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
This. doGet (request, response );
}
}

Javascript: verify. jsCopy codeThe Code is as follows: <! -- (1) Check the user name and use ajax in the jquery package to dynamically verify form data -->
Function verify1 (){
// 1. Obtain the content in the text box
// Document. getElementById ("username ");
Var jqueryObj = $ ("# username ");
// Obtain the node Value
Var userName = jqueryObj. val ();
// 2. Send the data in the text box to the server's servlet
$. Get ("AJAXServer? Name = "+ username, null, callback );
}
Function callback (data ){
// 3. receive the data returned by the server
// 4. dynamically display the data returned by the server on the page
// Find the node that saves the information
Var resultObj = $ ("# result ");
ResultObj.html (data );
}
// Verification method 2 is to write verification method 1 in a method, and the results are the same, all of which use ajax dynamic validation form data encapsulated by jquery
Function verify2 (){
$. Get ("AJAXServer? Name = "+ $ (" # username "). val (), null, function (data ){
$ ("# Result" pai.html (data );
});
}
<! -- (2) Check the user name and use the XMLHTTPRequest object for asynchronous ajax data verification -->
Var xmlhttp; // defines a global variable.
Function verify3 (){
// 1. Use dom to obtain the attribute values in the text box
Var username = document. getElementById ("username"). value;
// 2. Create an XMLHttpRequest object
// You need to create different methods of writing code for this object based on the differences between IE and other types of browsers.
If (window. XMLHttpRequest ){
// For FireFox, IE7, IE8, Safari, Opera, and javasillar
Xmlhttp = new XMLHttpRequest ();
// Fix bugs in some specific versions of javasillar browsers
If (xmlhttp. overrideMimeType ){
Xmlhttp. overrideMimeType ("text/html ");
}
} Else if (window. ActiveXObject ){
// For IE6, IE5.5, and IE5
// Two control names used to create the XMLHttpRequest object are saved in a js array. The previous version is newer.
Var activexName = ["MSXML2.XMLHTTP", "Microsoft. XMLHTTP"];
For (var I = 0; I <activexName. length; I ++ ){
// Retrieve a control name to create the control. If the control name is successfully created, terminate the loop.
// If creation fails, an exception is thrown. You can continue the loop and try again.
Try {
Xmlhttp = new ActiveXObject (activexName [I]);
Break;
} Catch (e ){
}
}
}
If (! Xmlhttp ){
Alert ("XMLHttpRequest object creation failed !! ");
Return;
}
// 3. register the callback function. When registering the callback function, you only need the function name. Do not add brackets.
// We need to register the function name. If brackets are added, the return value of the function will be registered. This is incorrect.
Xmlhttp. onreadystatechange = callback3;
// 4. Set connection information
Xmlhttp. open ("GET", "AJAXServer? Name = "+ username, true );
// 5. Send data and start interaction with the server.
Xmlhttp. send (null); // the user name is encapsulated in the GET url, so only one null value is used for sending.
// Request and send data in POST Mode
<! --
Xmlhttp. open ("POST", "AJAXServer", true );
Xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
Xmlhttp. send ("name =" + username );
-->
}
// Callback function
Function callback3 (){
// Determine whether the interaction between objects is complete
If (xmlhttp. readyState = 4 ){
// Determine whether http interaction is successful
If (xmlhttp. status = 200 ){
// Obtain the data returned by the server
// Method 1: Obtain plain text data output by the server
Var responseText = xmlhttp. responseText;
// Display the data on the page and find the Element Node corresponding to the div label through dom
Var divNode = document. getElementById ("result ");
// Set the html content in the Element Node
DivNode. innerHTML = responseText;
}
}
}

Web. xmlCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
Version = "2.5">
<Servlet>
<Servlet-name> AJAXServer </servlet-name>
<Servlet-class> AJAXServer </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> AJAXServer </servlet-name>
<Url-pattern>/AJAXServer </url-pattern>
</Servlet-mapping>
</Web-app>

Web. xmlCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
Version = "2.5">
<Servlet>
<Servlet-name> AJAXServer </servlet-name>
<Servlet-class> AJAXServer </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> AJAXServer </servlet-name>
<Url-pattern>/AJAXServer </url-pattern>
</Servlet-mapping>
</Web-app>

1. web. xml servlet Configuration

2. AJAXServer. java package name

1:

2:

3:

4:

Note: The above four URLs are all the same, but I didn't cut them down for ease of display.

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.