Highly recommended-1/3 pages of articles required by ajax developers

Source: Internet
Author: User

VII. AJAX Development
Now, you can clearly understand what AJAX is, what AJAX can do, and what AJAX is not. If you think AJAX can improve your development work, continue to see how to use AJAX.

7.1 AJAX application technology
Among the seven technologies involved in AJAX, I personally think Javascript, XMLHttpRequest, DOM, and XML are useful.

A. XMLHttpRequest object
XMLHttpRequest is the object of the XMLHTTP component. With this object, AJAX can exchange data only with the server like a desktop application, instead of refreshing the interface every time, you do not need to hand over data processing to the server every time. This reduces the server load, speeds up response, and shortens user waiting time.

Starting from IE5.0, developers can use the XMLHTTP ActiveX component in the Web page to expand their functions. They can directly transmit data to the server or receive data from the server without having to navigate the current Web page ., Mozilla1.0 and NetScape7 are used to create the XMLHttpRequest agent class that inherits XML. In most cases, the XMLHttpRequest object is similar to the XMLHTTP component. The method and attribute are similar, but some attributes are different.

XMLHttpRequest object initialization: <script language = "javascript"> var http_request = false; // IE browser http_request = new ActiveXObject ("Msxml2.XMLHTTP"); http_request = new ActiveXObject ("Microsoft. XMLHTTP "); // Mozilla Browser http_request = new XMLHttpRequest (); </script>

XMLHttpRequest object method:

Method Description
Abort ()

Stop current request

GetAllResponseHeaders ()

Returns the complete headers as a string.

GetResponseHeader ("headerLabel ")

Returns a single header tag as a string.

Open ("method", "URL" [, asyncFlag [, "userName" [, "password"]) Set the target URL, method, and other parameters for pending requests
Send (content) Send request
SetRequestHeader ("label", "value ") Set the header and send it together with the request

Attributes of the XMLHttpRequest object:

Attribute Description
Onreadystatechange Event triggers with status changes
ReadyState Object status (integer ):

 


0 = not initialized
1 = reading
2 = read
3 = interaction in progress
4 = complete
ResponseText The text version of the data returned by the server process
ResponseXML XML document objects compatible with DOM returned by Server Processes
Status Status Code returned by the server, such as: 404 = "file not found", 200 = "successful"
StatusText Status text returned by the server

B. Javascript
Javascript has been positioned as the script language of the client. The most widely used field is form data validation. Now, you can use Javascript to operate XMLHttpRequest to deal with databases.

C. DOM
DOM (Document Object Model) is a set of Apis provided for HTML and XML. It provides the file expression structure and can be used to change the content and visible objects. The scripting language can interact with the page through DOM. Web developers can operate and create file attributes, methods, and events in an object. For example, document indicates the page object itself.

D. XML
With XML (Extensible Markup Language), you can standardize the definition of structured data, which is consistent with the standards for data and documents transmitted online. Data and documents expressed in XML can be easily shared by all programs.

7.2 AJAX development framework
Here, we form a program framework for sending and receiving XMLHttpRequest requests through step-by-step parsing. In essence, AJAX follows the Request/Server mode, so the basic process of this framework is: object initialization, sending a Request, Server receiving, Server returning, client receiving, and modifying the content of the client page. However, this process is asynchronous.

A. initialize the object and send an XMLHttpRequest request
To allow Javascript to send HTTP requests to the server, the XMLHttpRequest object must be used. Before using XMLHttpRequest, you must instantiate the XMLHttpRequest object. As mentioned before, browsers have different implementations for this instantiation process. IE is provided in the form of ActiveX controls, while Mozilla and other browsers are provided directly in the form of XMLHttpRequest class. To enable the program to run across browsers, write as follows:
if (window.XMLHttpRequest) { // Mozilla, Safari, ...http_request = new XMLHttpRequest();}else if (window.ActiveXObject) { // IEhttp_request = new ActiveXObject("Microsoft.XMLHTTP");}

Some versions of Mozilla may encounter errors when processing content returned by the server that does not contain the XML mime-type header. Therefore, make sure that the returned content contains text/xml Information.

http_request = new XMLHttpRequest();http_request.overrideMimeType('text/xml');
B. Specified Response Handler
Next, you need to specify the client processing method when the server returns information. You only need to assign the corresponding handler name to the onreadystatechange attribute of the XMLHttpRequest object. For example:

 

http_request.onreadystatechange = processRequest;

If you need to specify this parameter, the function name is not enclosed in parentheses and no parameter is specified. You can also use Javascript to instantly define functions to define response functions. For example:

Http_request.onreadystatechange = function (){};

C. Send an HTTP request 

After the response processing function is specified, an HTTP request can be sent to the server. In this step, call the open and send methods of the XMLHttpRequest object.

http_request.open('GET', 'http://www.example.org/some.file', true);http_request.send(null);

The first parameter of open is the HTTP request method, which is Get, Post, or Head.

The second parameter of open is the target URL. Based on security considerations, this URL can only be of the same domain, otherwise the error "no permission" will be prompted. This URL can be any URL, including pages that require server interpretation and execution, not just static pages. The target URL Processing request XMLHttpRequest is the same as processing a common HTTP request. For example, JSP can use request. getParameter ("") or request. getAttribute ("") to obtain the URL parameter value.

The third parameter of open only specifies whether to continue executing the following code during the waiting time for the server to return information. If it is True, the execution will not continue until the server returns information. The default value is True.

In order, the send method must be called after the open call is completed. If the send parameter is sent in Post mode, it can be any content that you want to send to the server. However, like form, if you want to upload files or Post content to the server, you must first call the setRequestHeader method to modify the MIME category. As follows:

http_request.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);

In this case, the information is listed as a query string as the sned parameter, for example:

name=value&anothername=othervalue&so=on
D. process the information returned by the server
In the second step, we have specified the response processing function. In this step, let's see what the response processing function should do.

First, it checks the readyState value of the XMLHttpRequest object to determine the current status of the request. As you can see from the Attribute Table above, when the value of readyState is 4, it means that the server has returned all the information, and you can start to process the information and update the page content. As follows:

If (http_request.readyState = 4) {// The information has been returned. You can start processing} else {// the information has not been returned. Wait}

After the server returns the information, you also need to determine the returned HTTP status code to confirm that the returned page has no error. All status codes can be found on the W3C official website. 200 indicates that the page is normal.

If (http_request.status = 200) {// The page is normal and you can start to process the information} else {// The page has a problem}

XMLHttpRequest provides two Processing Methods for successfully returned information:
ResponseText: Use the returned information as a string;
ResponseXML: When the returned information is used in an XML document, it can be processed using DOM.

E. A preliminary development framework
To sum up the above steps, we have compiled a preliminary available development framework for future calls. Here, we use window. alert to display the information returned by the server as a string:
<Script language = "javascript"> var http_request = false; function send_request (url) {// initialize, specify the processing function, and send the request function http_request = false; // start initializing the XMLHttpRequest object if (window. XMLHttpRequest) {// Mozilla http_request = new XMLHttpRequest (); if (http_request.overrideMimeType) {// set the MiME category http_request.overrideMimeType ("text/xml");} else if (window. activeXObject) {// IE browser try {http_request = new ActiveXObject ("Msxml2. XMLHTTP ") ;}catch (e) {try {http_request = new ActiveXObject (" Microsoft. XMLHTTP ") ;}catch (e) {}} if (! Http_request) {// exception. window. alert ("the XMLHttpRequest object instance cannot be created. "); return false;} http_request.onreadystatechange = processRequest; // determine the request sending method and URL, and whether to execute the following code simultaneously: http_request.open (" GET ", url, true ); http_request.send (null);} // function processRequest () {if (http_request.readyState = 4) {// judge the object status if (http_request.status = 200) {// information returned successfully. start processing the information alert (http_request.responseText);} else {/ /Page abnormal alert ("the page you requested has an exception. ") ;}}</Script>
7.3. Simple Example
Next, we will use the above development framework for two simple applications.

A. Data Verification
In user registration forms, it is often used to check whether the user name to be registered is unique. The traditional method is to use window. open pop-up window or window. showModalDialog dialog box. However, both of them need to open the window. After AJAX is used, parameters are directly submitted to the server in asynchronous mode, and window. alert is used to display the verification information returned by the server. The Code is as follows:

Add a form code between <body> </body>:

<Form name = "form1" action = "" method = "post">
Username: <input type = "text" name = "username" value = ">
<Input type = "button" name = "check" value = "Uniqueness check" onClick = "userCheck ()">
<Input type = "submit" name = "submit" value = "submit">
</Form>

Add a call function based on the development framework:

Function userCheck () {var f = document. form1; var username = f. username. value; if (username = "") {window. alert ("the user name cannot be blank. "); F. username. focus (); return false;} else {send_request ('sample1 _ 2.jsp? Username = '+ username );}}

Let's see what sample1_2.jsp has done:

<% @ Page contentType = "text/html; charset = gb2312" errorPage = "" %> <% String username = request. getParameter ("username"); if ("educhina ". equals (username) out. print ("the user name has been registered. Please change to another user name. "); Else out. print (" the user name has not been used. You can continue. "); %>

Run it. Well, there is no pop-up window, no page refresh, and the effect is the same as expected. If necessary, you can implement more complex functions in sample00002.jsp. Finally, you only need to print out the feedback.


B. cascading menu
In Part 5, we mentioned how to use AJAX to improve the cascade menu design. Next, we will demonstrate how to "retrieve data on demand ".

First, add the following HTML code in the middle of <body> </body>:

<Table width = "200" border = "0" cellspacing = "0" cellpadding = "0"> <tr> <td height = "20"> <a href = "javascript: void (0) "onClick =" showRoles ('pos _ 1') "> Manager </a> </td> </tr> <tr style =" display: none "> <td height =" 20 "id =" pos_1 "> </td> </tr> <td height =" 20 "> <a href =" javascript: void (0) "onClick =" showRoles ('pos _ 2') "> Development Department </a> </td> </tr> <tr style =" display: none "> <td id =" pos_2 "height =" 20 "> </td> </tr> </table>

Add a response function showRoles (obj) based on the framework ):

// Display the job function showRoles (obj) {document. getElementById (obj ). parentNode. style. display = ""; document. getElementById (obj ). innerHTML = "reading data... "currentPos = obj; send_request (" sample2_2.jsp? PlayPos = "+ obj );}

Modify the processRequest function of the framework:

// Function processRequest () {if (http_request.readyState = 4) {// determines the object status if (http_request.status = 200) {// information returned successfully, start processing information document. getElementById (currentPos ). innerHTML = http_request.responseText;} else {// page abnormal alert ("the page you requested has an exception. ");}}}

Smaple2_2.jsp:

<% @ Page contentType = "text/html; charset = gb2312" errorPage = "" %>
<%
String playPos = request. getParameter ("playPos"); if ("pos_1 ". equals (playPos) out. print ("General Manager <br> Deputy General Manager"); else if ("pos_2 ". equals (playPos) out. println ("Chief Engineer <br> Software Engineer ");
%>

Run the following command to check the effect:

7.4 Document Object Model (DOM)
The Document Object Model (DOM) is an application interface (API) that represents documents (such as HTML and XML), accesses, and operations that constitute various elements of a document ). Generally, all browsers that support Javascript support DOM. The DOM involved in this article refers to the standard Document Object Model defined by W3C. It represents HTML and XML documents in a tree structure, defines the methods and attributes for traversing the tree and checking and modifying the node of the tree.

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.