jquery Ajax Learning notes one _jquery

Source: Internet
Author: User

Ajax Brief Introduction:
AJAX refers to asynchronous JavaScript and XML (asynchronous JavaScript and XML), a Web development technology that creates interactive Web applications. The ajax,javascript can be used to communicate directly with the server by using the XMLHttpRequest object of JavaScript. With this object, you can use JavaScript to exchange data with the WEB server without overloading the page.
jquery is a JavaScript framework, a lightweight encapsulation of JavaScript that is easy to understand.
Ajax is a kind of asynchronous request technology combined by Xml+javascript. Enables dynamic refresh.
Ajax prep work:
1.jquery Download:
The latest download address of the official website: http://blog.jquery.com/2011/09/01/jquery-1-6-3-released/
Select jquery 1.6.3 minified or jquery 1.6.3 uncompressed right click on download to select "Use Thunder Download"
2. Introduction of Main knowledge
2.1.ajax Asynchronous Transmission steps:
1. Get the value of a property in a text box using DOM
document.getElementById ("ID name"). Value
2. Create a XMLHttpRequest Object
According to the browser's different have XMLHttpRequest, activexobject two kinds of objects
3. Registration callback function Registration callback function, only need function name, do not parentheses
Registering the callback function gets the data returned by the server side:
The first way: Get the server-side output of plain text data
The second way: to accept the DOM object of an XML data object using the Responsexml method
4. Set up connection information
5. Send data and start interacting with the server side
Post mode/get mode

2.2.ajax Main methods:
(1). getElementById ("id attribute value"):
object is worthwhile based on the id attribute specified
(2). getElementsByTagName (tagname):
Returns the collection of elements of the specified name by looking for any HTML element in the entire HTML document
(3). Selector:
The selector has a basic selector, a hierarchy selector, a property selector, and so on. This program only to the basic selector #id, such as:
$ ("#myDiv"): Find element with ID "Mydiv"
2.3.XMLHttpRequest objects:
XMLHttpRequest can provide updates to the page without reloading the page, request data from the client to the server after the page is loaded, accept data on the server side after the page is loaded, and send data to the client in the background.
2.3.1. Method:
(1) Overridemimetype ("text/html"):
The header is sent to the server, forcing Text/xml as Mime-type
(2) Open (method, URL, async, username, password):
Initializes HTTP request parameters, such as URLs and HTTP methods, but does not send requests.
Method parameters are HTTP methods for the request, including get, post, and head;
The URL parameter is the body of the request
The Async parameter indicates whether the request uses synchronous or asynchronous, false requests are synchronous, and true requests are asynchronous
The username and password parameters are optional and are qualified for the authorization required for the URL. If specified, they overwrite any qualifications specified by the URL itself.
(3) Send (body):
Sends an HTTP request, using an argument passed to the open () method, and an optional request body passed to the method
Send (body), as a string or Document object, if the HTTP method specified by calling open () is a POST or put,body parameter that specifies the requestor. This parameter is null if the request body is not required.
If the previously called open () parameter async to False, this method blocks and does not return until ReadyState is 4 and the server's response is fully received.
If the async parameter is true, or if this argument is omitted, send () returns immediately, and as described later, the server response is processed in a background thread
(4) setRequestHeader (name, value):
Set or add an HTTP request to an open but unsent request
The name parameters are the names of the headers you want to set. This parameter should not include white space, colon, or line wrapping.
The value parameter is the values of the head. This parameter should not include line wrapping
2.3.2. Properties:
(1) onReadyStateChange:
The event handle function that is invoked each time the ReadyState attribute changes. When ReadyState is 3 o'clock, it may also be called multiple times.
(2) ReadyState:
The status of the HTTP request. When a XMLHttpRequest is first created, the value of this property starts at 0 until the full HTTP response is received, and the value increases to 4.
Each of the 5 states has an associated informal name, and the following table lists the status, name, and meaning:

The value of the readyState is not decremented unless the abort () or open () method is invoked when a request is in process. Each time the value of this property is incremented, the onReadyStateChange event handle is triggered.
(3) Status:
The HTTP status code returned by the server, such as 200, indicates success, while 404 indicates a "not Found" error. Reading this property when ReadyState is less than 3 results in an exception.
(4) ResponseText:
The response body received so far from the server (excluding the head), or if the data has not yet been received, is an empty string.
If ReadyState is less than 3, this property is an empty string. When ReadyState is 3, this property returns the part of the response that is currently received. If ReadyState is 4, this property holds the complete response body.
If the response contains a header that specifies a character encoding for the body of the response, the encoding is used. Otherwise, assume the use of Unicode UTF-8
(5) Responsexml: Response to the request, parsing to XML and returning as a Document object

code example:
Note: This example has the foreground and the backstage composition, the backstage uses is the servlet realization, just did not go to the database verifies the data. The foreground has the HTML and the JavaScript composition, the foreground verification has adopted two kinds of methods, one is using the jquery encapsulation Ajax to realize the form dynamic verification, the second is uses the XMLHttpRequest object to realize the form dynamic verification, The difference between the two modes of authentication is that the JavaScript script is different, and the foreground page is the same as the servlet in the background.

Front desk ajax.html

Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"
"Http://www.w3.org/TR/html4/loose.dtd" >
<title>ajax</title>
<!--import JS, pay attention to the path of SRC-->
<script type= "Text/javascript" src= "Jslib/jquery.js" ></script>
<script type= "Text/javascript" src= "Jslib/verify.js" ></script>
<body>
<!--Ajax does not require forms for data submission, so you do not need to write form labels-->
<!--Ajax does not require a name attribute, it requires an attribute of an ID-->
<!--onblur event occurs when the object loses focus-->
User name: <input type= "text" id= "username" onblur= "verify3 ()"/><div id= "result" ></div>
</br></br>
<input type= "Submit" value= "Login" onclick= "login ()"/>
</body>

Backstage Ajaxserver.java:
Copy Code code 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 parameters
String old=request.getparameter ("name");
2. Check if there are any problems
if (old==null| | Old.length () ==0) {
Out.println ("User name cannot be empty");
}else{
3. Check operation
String Name=old;
if (Name.equals ("Pan")) {
4. Different from the traditional application. This step needs to return the data that the user is interested in to the page end, not to the new page
Out.println ("User name [" +name+ "] already exists");
}else{
Out.println ("User name [" +name+ "] can be used");
}
}
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
This.doget (Request,response);
}
}

Javascript:verify.js
Copy Code code as follows:

<!--(1) User name verification, using jquery encapsulated Ajax dynamic Calibration form data-->
function Verify1 () {
1. Get the contents of the text box
document.getElementById ("username");
var jqueryobj= $ ("#username");
Get the value of a node
var username=jqueryobj.val ();
2. The servlet that sends data from a text box to the server
$.get ("ajaxserver?name=" +username,null,callback);
}
function callback (data) {
3. Data returned by the receiving server
4. Dynamically display the data returned by the server side on the page
Locate the node that holds the information
var resultobj=$ ("#result");
resultobj.html (data);
}
Validation Method 2 is the validation mode 1 written in a method, the effect is the same, are using the jquery encapsulated Ajax dynamic Check form data
function Verify2 () {
$.get ("Ajaxserver?name=" +$ ("#username"). Val (), null,function (data) {
$ ("#result"). HTML (data);
});
}
<!--(2) User name verification, using XMLHttpRequest object for AJAX asynchronous data validation-->
var xmlhttp;//defines a global variable
function Verify3 () {
1. Get the value of a property in a text box using DOM
var Username=document.getelementbyid ("username"). Value;
2. Create a XMLHttpRequest Object
Need to write different code for different ways of creating this object for IE and other types of browser differences
if (window. XMLHttpRequest) {
For Firefox,ie7,ie8,safari,opera,mozillar
Xmlhttp=new XMLHttpRequest ();
Fixes bugs for specific versions of the Mozillar browser
if (Xmlhttp.overridemimetype) {
Xmlhttp.overridemimetype ("text/html");
}
else if (window. ActiveXObject) {
For IE6,IE5.5,IE5
Two control names that can be used to create XMLHttpRequest objects, stored in a JS array, in the previous version of the newer
var activexname=["MSXML2. XMLHTTP "," Microsoft.XMLHTTP "];
for (Var i=0;i<activexname.length;i++) {
Take out a control name to create and terminate the loop if the creation succeeds
If the creation fails, an exception is thrown, and then you can continue the loop and try to create
try{
Xmlhttp=new ActiveXObject (Activexname[i]);
Break
}catch (e) {
}
}
}
if (!xmlhttp) {
Alert ("XMLHttpRequest object creation failed!!") ");
Return
}
3. Registration callback function Registration callback function, only need function name, do not parentheses
We need to register the function name, and if we add parentheses, we'll register the return value of the function, which is wrong.
Xmlhttp.onreadystatechange=callback3;
4. Set up connection information
Xmlhttp.open ("Get", "ajaxserver?name=" +username,true);
5. Send data and start interacting with the server side
Xmlhttp.send (null); The user name is encapsulated in the//get URL, so sending only sends a NULL
Post mode request and send data
<!--
Xmlhttp.open ("POST", "Ajaxserver", true);
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Xmlhttp.send ("name=" +username);
-->
}
callback function
function Callback3 () {
To determine whether the state of an object is interactively completed
if (xmlhttp.readystate==4) {
To determine if HTTP interaction is successful
if (xmlhttp.status==200) {
Getting data returned by the server side
The first way: Get the server-side output of plain text data
var Responsetext=xmlhttp.responsetext;
Display the data on the page by Dom to find the element node for the DIV tag
var Divnode=document.getelementbyid ("result");
To set the contents of HTML in an element node
Divnode.innerhtml=responsetext;
}
}
}

Xml
Copy Code code 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>

Xml
Copy Code code 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>

Configuration of the 1.web.xml servlet

2.ajaxserver.java Package Name Related

Screenshot 1:

Screenshot 2:

Screenshot 3:

Screenshot 4:

Screenshot Description: The above four screenshots URL display is the same, just for the sake of showing I did not cut it down.

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.