Introduction to AJAX

Source: Internet
Author: User

Ajax is considered to be (ASynchronous (asynchronous)JAvaScriptANdXMl ). Currently, Ajax is a technology that allows the browser to communicate with the server without refreshing the current page.

Synchronization refers to the communication mode in which the sender sends a packet only after the receiver sends a response.
Asynchronous means that the sender sends the next packet instead of sending the response from the receiver.
Generally, you do not need to refresh the webpage to communicate with the server:
  • Flash
  • Framework Frameset: If a Web page is constructed using a set of frameworks, you can update only one of the frameworks without disturbing the entire page.
  • XMLHttpRequest: This object is an extension of JavaScript that enables the webpage to communicate with the server. Is the best choice for creating Ajax applications. In fact, Ajax is usually used as a synonym for XMLHttpRequest (XHR) objects.
1. Ajax Working principle
  • AJAX adopts Asynchronous interaction. AJAX introduces an intermediate media between the user and the server, thus eliminating the disadvantages of processing-waiting-processing-waiting during network interaction.

  • Your browser loads the AJAX engine when executing tasks. The AJAX engine is written in JavaScript language and is usually hidden in a hidden framework. It compiles the user interface and interacts with the server.

  • The AJAX engine allows Asynchronous interaction between users and applications, independent of communication between users and network servers. Now, you can use Javascript to call the AJAX engine to generate an HTTP user action, the data editing, page navigation, and data validation in the memory do not need to be re-loaded to the entire page, which can be executed by AJAX.

2, AJAX Defects
  • AJAX uses a lot of JavaScript and AJAX engines, depending on the support of browsers. IE5.0 and later versions, Mozilla1.0, NetScape7 and later versions are supported. Although Mozilla also supports AJAX, XMLHttpRequest is provided in different ways. Therefore, AJAX programs must test the compatibility of various browsers.
  • When AJAX updates the page content, the entire page is not refreshed. Therefore, the page's back-up function is invalid. Some users often do not know whether the current data is old or updated. In this case, you need to clearly remind the user that "data has been updated ".
  • The support for streaming media is not as good as FLASH.
  • Some handheld devices (such as mobile phones and PDAs) cannot support Ajax yet.
3. Two different methods for creating AJAX engine objects

First:

Function createXHR () {var xhr = null; try {xhr = new ActiveXObject ("microsoft. xmlhttp ");} catch (e) {try {xhr = new XMLHttpRequest ();} catch (e) {alert (" the browser is too bad, dare to unmount it ");} return xhr ;}


Second:

function createXHR(){    var xhr=null;    if(window.ActiveXObject){    xhr= new ActiveXObject("microsoft.xmlhttp");    }else{    xhr = new XMLHttpRequest();    }    return xhr;    }

4. Use AJAX

Core functions: functions that start when a js event is initiated

Function checkValue () {// create the ajax engine object var xhr = createXHR (); // used to store the returned information var msg = ""; // create an ajax status listener xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {// accept the returned string msg = xhr. responseText; // use the returned string information document. getElementById ("result "). innerHTML = msg ;}}; var username = document. getElementsByName ("username") [0]. value; // prepare to send the request xhr in POST mode. open ("post", "/day31/CheckServlet? Time = "+ new Date (). getTime (); // sets the request header. This request header is set only in POST mode. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); // when it is set to post, you can add a parameter list in the send function. If it is get, the following send parameter is null. Xhr. send ("username =" + username );}


Add the time parameter to the url because in some cases, Some browsers cache the results of multiple XMLHttpRequest requests in the same URL. If the response to each request is different, this will bring bad results. Append the current timestamp to the end of the URL to ensure the uniqueness of the URL, so as to avoid the browser cache result onreadystatechange: Event trigger of status change.

ReadyState: Object status

0: not initialized

1: Reading

2: Read

3: Interaction in progress

4: complete

ResponseText: returned Text Version

ResponseXML: the XML document object that returns data compatible with DOM.

Status: status Code returned by the server, for example, 404: The file is not found, 200: Successful

Three key parts of interaction between the XMLHttpRequest instance and the server:

  • Onreadystatechange event handler:

This event is triggered by the server, not the user. During ajax execution, the communication status of the current client of the server comrade is changed (that is, the readState of the XMLHttpRequest object is changed ). The onreadystatechange event is triggered every time the server changes the communication status of the client.

  • Open (method, url, asynch)

The front-end sends a request to the server through the open method of the XMLHttpRequest object.

Method: Request type, which is a string similar to "GET" or "POST. If you only want to retrieve a file from the server without sending any data, use GET (you can send data in a GET request by appending the query string on the URL, however, the data size is limited to 2000 characters ). To send data to the server, use POST. Url: the path string pointing to the file on the server you requested. It can be an absolute or relative path. Asynch: indicates whether the request needs to be asynchronously transmitted. The default value is true (asynchronous ). Specify true. You do not need to wait for the server to respond before reading the subsequent script. Specify false. When the script processing process passes through this point, it stops until the Ajax request is executed.
  • Send (data)
• The open method defines some details about Ajax requests. The send method can send commands for standby requests • data: the string to be passed to the server. • If a GET request is selected, no data is sent, and null is passed to the send method: request. send (null); • when providing parameters to the send () method, make sure that the method specified in open () is POST. If no data is sent as part of the Request body, null is used.
5. Ajax server programs

In the ajax server, response. getWriter (). write (msg); is used to return ajax return information.

However, before executing this function, you must specify the type of returned information:

1. resp. setContentType ("text/html; charset = UTF-8"); indicates that a text file is returned.

2. response. setContentType ("text/xml; charset = UTF-8"); the returned xml file

 

 

 


 

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.