Highly recommended-ajax developers must read the article 1th/3 page _ajax related

Source: Internet
Author: User
Tags object model

Seven, Ajax development
Here, you can already know what Ajax is, what Ajax can do, and where the Ajax is bad. If you think Ajax is really going to improve your development effort, go ahead and see how to use Ajax.

7.1, AJAX applications to the technology
Of the 7 technologies involved in Ajax, individuals think JavaScript, XMLHttpRequest, DOM, and XML are more useful.

A, XMLHttpRequest objects
XMLHttpRequest is the object of the XMLHTTP component, through which Ajax can only exchange data levels with the server like a desktop application, without refreshing the interface every time, and without handing over data processing to the server every time. This reduces the server burden, accelerates the response speed, and shortens the time that users wait.

IE5.0 begins, developers can use the XMLHTTP ActiveX component inside a Web page to extend their functionality without having to navigate directly from the current Web page to the server or receive data from the server. , Mozilla1.0 and NetScape7 are proxy classes that create inherited XML XMLHttpRequest; For most cases, XMLHttpRequest objects are similar to XMLHTTP components, with methods and properties similar, except for partial properties.

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>

Ways to XMLHttpRequest objects:

Method Describe
Abort ()

Stop current request

getAllResponseHeaders ()

Returns the complete headers as a string

getResponseHeader ("Headerlabel")

Returns a single header label as a string

Open ("Method", "URL" [, asyncflag[, "UserName" [, "Password"]]) Set the target URL, method, and other parameters of pending requests
Send (content) Send Request
setRequestHeader ("label", "value") Set header and send along with request

Properties of the XMLHttpRequest object:

Property Describe
onReadyStateChange Event triggers for state changes
ReadyState Object State (integer):


0 = not initialized
1 = in read
2 = Read
3 = in interaction
4 = Complete

ResponseText The server process returns a text version of the data
Responsexml The XML Document object that the server process returns the data as a compatible DOM
Status The status code returned by the server, such as: 404 = "File not found", 200 = "Success"
StatusText Status text information returned by the server

B
Javascript
JavaScript has always been positioned as a scripting language for clients, and the most widely used is the validation of form data. Now, you can work with a database by using JavaScript to manipulate XMLHttpRequest.

C
Dom
DOM (document Object Model) is a set of APIs that is provided to HTML and XML, provides a presentation structure for the file, and can be used to change the content and visibility of it. Scripting languages can interact with pages through the DOM. The properties, methods, and events that Web developers can manipulate and create files are presented as objects. For example, document represents the Page object itself.

DXml
Through XML (extensible Markup Language), we can standardize the definition of structured data, the data and documents transmitted on the Internet conform to the unified standard. Data and documents expressed in XML can be easily shared by all programs.

7.2, AJAX development Framework
Here, we use step-by-step parsing to form a program framework for sending and receiving XMLHttpRequest requests. Ajax essentially follows the request/server pattern, so the basic process of this framework is also: object initialization à send request à server receive à server return à client receive à modify client page content. It's just that the process is asynchronous.

A, initialize the object, and issue a XMLHttpRequest request
In order for JavaScript to send HTTP requests to the server, you must use the XMLHttpRequest object. Before you can use it, instantiate the XMLHttpRequest object first. As I said before, different browsers implement this instantiation process differently. IE is provided in the form of ActiveX controls, while browsers such as Mozilla are provided directly in the form of XMLHttpRequest classes. In order for the program to be written to run across browsers, write this:
if (window. XMLHttpRequest) {//Mozilla, Safari, ...
Http_request = new XMLHttpRequest ();
}
else if (window. ActiveXObject) {//IE
http_request = new ActiveXObject ("Microsoft.XMLHTTP");
}

Some versions of Mozilla browsers can make mistakes when processing server-returned content that does not contain XML Mime-type header information. Therefore, make sure that the returned content contains text/xml information.

Http_request = new XMLHttpRequest ();
Http_request.overridemimetype (' Text/xml ');
B, specifying response handler functions
Next, you specify how the client handles when the server returns information. Just assign the corresponding handler name to the onReadyStateChange property of the XMLHttpRequest object. Like what:

Http_request.onreadystatechange = ProcessRequest;

When you need to point out, this function name does not have parentheses and does not specify a parameter. You can also define a response function in a way that JavaScript instantly defines a function. Like what:

Http_request.onreadystatechange = function () {};

C, issuing an HTTP request

After you specify the response processing function, you can send an HTTP request to the server. This step invokes the XMLHttpRequest object's open and send methods.

Http_request.open (' Get ', ' http://www.example.org/some.file ', true);
Http_request.send (NULL);

The first argument to open is the method for the HTTP request, for GET, post, or head.

The second argument to open is the destination URL. Based on security considerations, this URL can only be in the same domain, or you will be prompted with "No Permissions" error. This URL can be any URL, including a page that requires the server to interpret the execution, not just static pages. The Target URL processing request XMLHttpRequest request is the same as processing a normal HTTP request, such as JSP can use Request.getparameter ("") or Request.getattribute ("") to get the URL parameter values.

The third parameter of open simply specifies whether to continue with the following code while waiting for the server to return information. If true, the execution will not continue until the server returns information. The default is true.

In order, the Send method is called after the open call completes. If the send parameter is sent as a post, it can be anything you want to pass to the server. However, as with form, if you want to transfer files or post content to the server, you must first call the setRequestHeader method and modify the MIME category. As follows:

Http_request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

The data is then listed as a query string, as a sned parameter, for example:

Name=value&anothername=othervalue&so=on
D, processing the information returned by the server
In the second step we have specified the response handler function, which is a step to see what the response handler should do.

First, it checks the readystate value of the XMLHttpRequest object to determine the current state of the request. Reference to the previous property sheet can be known, readystate value of 4, on behalf of the server has returned all the information, you can start processing information and update the content of the page. As follows:

if (http_request.readystate = = 4) {
//information has returned, can start processing
} else {
//information has not returned, wait
}

After the server returns the information, it also needs to determine the HTTP status code returned, and make sure the returned page has no errors. All status codes can be found on the official website of the world's Web site. Of these, 200 represents the normal page.

if (Http_request.status = =) {
//page normal, you can start processing information
} else {
//page has a problem
}

XMLHttpRequest has two ways of handling the information that is successfully returned:
ResponseText: Use the returned information as a string;
Responsexml: The returned information is used as an XML document and can be processed using DOM.

E, a preliminary development framework
Summarizing the above steps, we have sorted out an initial usable development framework for later invocation, where the information returned by the server is displayed as a string Window.alert:
<script language= "JavaScript" > var http_request = false; function send_request (URL) {//Initialize, specify handler function, send request Http_request = false;//start Initializing XMLHttpRequest object if window. XMLHttpRequest) {//mozilla browser http_request = new XMLHttpRequest (); if (Http_request.overridemimetype) {//Set 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, create object instance failed Window.alert ("Cannot create XMLHttpRequest object instance."); return false;} Http_reque
St.onreadystatechange = ProcessRequest;
Determine how and when the request was sent, and whether to synchronize the next code http_request.open ("Get", url, True);
Http_request.send (NULL);  //processing return information functions function ProcessRequest () {if (http_request.readystate = 4) {///Judging Object state if (Http_request.status = 200) {
The information has been successfully returned and the information alert (HTTP_REQUEST.RESPONSETEXT) has been processed; else {//page is not normal alert ("the page you are requesting has an exception.)
");
}
}
} </script>
7.3, a simple example
Next, we use the development framework above to make two simple applications.

A, data validation
In a user-registered form, it is common to see if you want to verify that the username you are registering is unique. The traditional approach is to use a window.open pop-up window, or a window. ShowModalDialog dialog box. However, both of these need to open the window. With Ajax, the parameters are directly submitted to the server in an asynchronous manner, and the verification information returned by the server is displayed with Window.alert. The code is as follows:

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

<form name= "Form1" action= "" method= "POST" >
User name: <input type= "text" name= "username" value= "" >
<input type= "button" name= "Check" value= "Uniqueness Check" onclick= "Usercheck ()" >
<input type= "Submit" name= "Submission" value= "submitted" >
</form>

Add another call function on the basis of the development framework:

function Usercheck () {
var f = document.form1;
var username = f.username.value;
if (username== "") {
window.alert ("User name cannot be empty.") ");
F.username.focus ();
return false;
}
else {
send_request (' sample1_2.jsp?username= ' +username);
}
}

Look what sample1_2.jsp did:

<%@ page contenttype= "text/html; charset=gb2312 "errorpage=" "%>
<%
String username = request.getparameter (" username ");
if ("Educhina". Equals (username)) Out.print ("User name is already registered, replace a user name.") ");
else Out.print ("User name has not been used, you can continue.") ");
%>

Run, um, no pop-ups, no page refreshes, as expected. More complex functionality can be implemented in sample1_2.jsp, if needed. Finally, just print out the feedback information.


B, cascading menu
In part fifth we mentioned using Ajax to improve the design of cascading menus. Next, we'll show you how to "fetch data on demand."

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

<table width= "border=" 0 "cellspacing=" 0 "cellpadding=" 0 ">
<tr>
<td height=" ">
<a href= "javascript:void (0)" onclick= "Showroles (' Pos_1 ')" > manager's Office </a>
</td>
</tr>
<tr style= "Display:none" >
<td height= "" id= "Pos_1" > </td>
</tr>
<tr >
<td height= ">
<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:

Displays post
function showroles (obj) {
document.getElementById (obj) under the department. ParentNode.style.display = "";
document.getElementById (obj). InnerHTML = "reading data ..."
currentpos = obj;
Send_request ("sample2_2.jsp?playpos=" +obj);
}

To modify the ProcessRequest function of a frame:

Functions that process return information function
ProcessRequest () {
if (http_request.readystate = 4) {//Judge object state
if (http_ Request.status = = 200) {//information has been successfully returned to begin processing information
document.getElementById (currentpos). InnerHTML = Http_ Request.responsetext;
} else {//page is not normal
alert ("The page you are requesting has an exception.) ");
}
}
}

The last is 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 a look at the effect:

7.4, Document Object Model (DOM)
A Document Object Model (DOM) is an application interface (API) that represents a document (such as HTML and XML) and accesses and operates the various elements that make up a document. In general, all browsers that support JavaScript support DOM. The DOM involved in this article refers to the standard document object model defined by the Consortium, which represents HTML and XML documents in a tree structure, and defines methods and properties for traversing the tree and checking and modifying the nodes of the tree.
Current 1/3 page 123 Next read the full text
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.