Ajax analysis and learning

Source: Internet
Author: User

Ajax is called Asynchronous JavaScript and XML (Asynchronous JavaScript and XML). It is a Web page development technology used to create interactive web applications. It uses: XHTML + CSS to represent information; JavaScript to operate the Document Object Model for Dynamic Display and interaction; XML and XSLT for data exchange and related operations; use the XMLHTTPRequest object for asynchronous data exchange with the Web server; use JavaScript to bind everything together.

XMLHTTPRequest object 

An object You Want To Know may be the most unfamiliar to you, that is, XMLHttpRequest. This is a JavaScript Object. It is very easy to create this object.

The XMLHTTPRequest object is an object that processes communications from all servers. Javascript is used to communicate with the server through the XMLHTTPRequest object.

Ajax basically stores JavaScript and XMLHttpRequest objects between web forms and servers. When a user fills out a form, the data is sent to some JavaScript code instead of directly sent to the server. On the contrary, JavaScript code captures form data and sends requests to the server. At the same time, forms on the user's screen do not flash, disappear, or delay. In other words, JavaScript code sends a request behind the scenes, and the user does not even know how to send the request. Even better, requests are sent asynchronously, that is, JavaScript code (and users) does not have to wait for the response from the server. Therefore, you can continue to input data, scroll the screen, and use applications. The server then returns the data to the JavaScript code (still in the web form), which decides how to process the data. It can quickly update the form data, making users feel that the application is completed immediately, the form is not submitted or refreshed, and users get new data. JavaScript code can even execute some calculation on the received data and send another request without user intervention! This is the power of XMLHttpRequest. It can interact with the server as needed, and the user may not even know what happened behind the scenes. The result is similar to the dynamic, rapid response, and highly interactive experience of desktop applications, but it has all the power of the Internet.

Add some JavascriptAfter obtaining the XMLHttpRequest handle, you can use JavaScript code to complete basic tasks:
Get form data: JavaScript code can easily extract data from HTML forms and send it to the server.
Modify the data on the form: Updating the form is also very easy, from setting the field value to quickly replacing the image.
Parse HTML and XML: use JavaScript code to manipulate the Dom and process the XML Data Structure returned by the HTML form server.

End with Dom 
There is also the Dom, that is, the Document Object Model. It is easy and intuitive to use DOM in javascript technology. You may need to explain how to use the Dom as usual, or at least give some sample code, but this may be misleading. Even if you ignore Dom, you can still explore Ajax in depth. When we need to pass XML and change HTML forms between JavaScript code and the server, we will study DOM in depth. You can do some interesting work without it, so now let's put the DOM aside.

Start learning Ajax GET request object 
With the basic knowledge above, it is very easy to get the XMLHTTPRequest object. XMLHttpRequest is the core of Ajax applications. But it is strange that XMLHttpRequest has become one of the victims of the war between browsers. Therefore, different methods may be required to obtain XMLHttpRequest objects in different browsers. Microsoft browser
Microsoft browser Internet Explorer uses the MSXML parser to process XML (for more information about MSXML, see references ). Therefore, if an Ajax application needs to work with Internet Explorer, an object must be created in a special way. But it is not that simple. Depending on the version of JavaScript technology installed in Internet Explorer, MSXML actually has two different versions. Therefore, you must write code for these two cases.
var xmlHttp = false; try {   xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {                    try {                            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                         } catch (e2) {                                           xmlHttp = false;                                           }               }

XMLHTTP = new activexobject ("msxml2.xmlhttp"); XMLHTTP = new activexobject ("Microsoft. XMLHTTP "); the two lines of code are to try to use MSXML of two versions to create an object. If it fails, use another version to create the object. If none of them are successful, set the XMLHTTP variable to false to tell you that the Code has a problem. This may occur because a non-Microsoft browser is installed and different codes are required.

Processing Mozilla and non-Microsoft browsers

VaR XMLHTTP = new XMLHTTPRequest object; this line of much simpler code is available in Mozilla, Firefox, Safari, opera, and basically all non-Microsoft browsers that support Ajax in any form or method, the XMLHTTPRequest object is created.

Support for all browsers var XMLHTTP = false; try {XMLHTTP = new activexobject ("msxml2.xmlhttp");} catch (e) {try {XMLHTTP = new activexobject ("Microsoft. XMLHTTP ") ;}catch (E2) {XMLHTTP = false ;}} if (! XMLHTTP & typeof XMLHttpRequest! = 'Undefined') {XMLHTTP = new XMLHttpRequest ();}

The core of this Code is divided into three steps:
1. Create a variable XMLHTTP to reference the XMLHTTPRequest object to be created.
2. Try to create this object in Microsoft browser:
1) try to create it using the msxml2.xmlhttp object.
2) if it fails, try the Microsoft. XMLHTTP object again.
3. If XMLHTTP is still not created, this object is created in non-Microsoft mode.
Finally, XMLHTTP should reference a valid XMLHTTPRequest object, regardless of the browser that runs.

Ajax request/Response

Send request
You already have a brand new XMLHTTPRequest object. Now let it do some work. First, you need a JavaScript method that can be called on a web page. The next step is basically the same process in all Ajax applications:
1. obtain the required data from the web form.
2. Create the URL to be connected.
3. Open the connection to the server.
4. Set the function to run after the server completes.
5. Send a request.

Function callserver () {// obtain the form information var city = document. getelementbyid ("city "). value; var state = document. getelementbyid ("state "). value; // If (city = NULL) | (city = "") return; If (State = NULL) | (State = "") return; // create the URL var url = "/scripts/getcode. aspx? City = "+ escape (city) +" & State = "+ escape (State); // open the XMLHTTP connection. open ("get", URL, true); // The function XMLHTTP. onreadystatechange = updatepage; // send the request XMLHTTP. send (null );}

The initial code is to use the basic JavaScript code to obtain the values of several form fields. Set An ASPX page script as the link target. Pay attention to the method specified by the Script URL. City and State (from the form) are used, and simple get parameters are appended after the URL. Then open a connection. This is the first time you see that XMLHttpRequest is used. The connection method (get) and the URL to be connected are specified. If the last parameter is set to true, an asynchronous connection is requested. If false is used, the code sends a request and waits for the response from the server. If this parameter is set to true, you can still use forms (or even call other Javascript methods) when the server processes requests in the background ).

The onreadystatechange attribute of XMLHTTP (XMLHTTPRequest object instance) can tell the server what to do after the operation is completed (it may take five minutes or five hours. Because the Code does not wait for the server, you must let the server know how to do so that you can respond. In this example, if the server finishes processing the request, a special method named updatepage () will be triggered.

Finally, use null to call send (). Because the data (city and state) to be sent to the server has been added to the request URL, no data needs to be sent in the request. In this way, a request is sent, and the server works according to your requirements.

Handling response

Do not do anything until the value of the XMLHTTP. readystate attribute is 4 (ready ).
The server fills in the response to the XMLHTTP. responsetext attribute. Use the XMLHTTP. responsetext attribute to obtain the server response.

if(req.readyState==4){        if(req.status == 200 ){  var msg = req.responseXML.getElementsByTagName("msg")[0];  document.getElementById("result").innerHTML = msg.childNodes[0].nodeValue;    }}

Validate. jsp document:

<%response.setContentType("text/xml");response.setHeader("Cache-Control","no-store");//HTTP1.1response.setHeader("Pragma","no-cache");//HTTP1.0response.setDateHeader("Expires",0);//prevents caching at proxy serverresponse.getWriter().write("<msg>valid</msg>");%>

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.