Ajax Boost (1) Getting Started

Source: Internet
Author: User

Learning Purpose: To understand Ajax and its working principles, an effective way to build a website.

Ajax is an abbreviation for asynchronous JavaScript and XML (as well as DHTML, etc.).

The following are the basic techniques used by AJAX applications:
? HTML is used to establish WEB forms and to determine the fields used by other parts of the application.
? JavaScript code is the core code that runs Ajax applications, helping to improve communication with server applications.
? DHTML or dynamic HTML, which is used to dynamically update the form. We'll use Div, span, and other dynamic HTML elements to tag the HTML.
? The Document Object Model DOM is used (through JavaScript code) to process the HTML structure and (in some cases) the XML returned by the server.

As can be seen from the above, Ajax is not a new technology, but a number of old technology through new methods to combine to achieve a new effect! A lot of things are diversified, it can be said that Ajax is a new technology, it can be said that Ajax is a novel idea, a new architecture!

The basic work principle and process of Ajax:

In a generic WEB application, users fill Out form fields and click the Submit button. The entire form is then sent to the server, the server forwards it to the script that handles the form (usually PHP or Java, or it could be a CGI process or something like that), and the script executes and then sends it back to the new page. The page might be HTML with a new form populated with some data, a confirmation page, or a page with some options selected based on the data entered in the original form. Of course, the user must wait while the script or program on the server processes and returns a new form. The screen becomes blank until the server returns data and then redraws. This is why interactivity is poor, and users don't get immediate feedback, so they feel different from desktop applications.

Ajax basically puts JavaScript technology 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 being sent directly to the server. Instead, the JavaScript code captures the form data and sends the request to the server. Also, the form on the user's screen does not blink, disappear, or delay. In other words, the JavaScript code sends the request behind the scenes, and the user doesn't even know that the request was made. Better yet, the request is sent asynchronously, meaning that the JavaScript code (and the user) does not wait for the server to respond. So users can continue to enter data, scroll the screen, and use the application.

The server then returns the data to the JavaScript code (still in the Web form), which determines how the data is processed. It can quickly update form data, making it feel that the application is done immediately, that the form is not committed or refreshed, and that the user gets new data. JavaScript code can even perform some sort of calculation on the received data and send another request without user intervention at all! This is where XMLHttpRequest the power is. It can interact with the server as needed, and users can even be completely unaware of what is going on behind the scenes. The result is a dynamic, responsive, highly interactive experience similar to desktop applications, but with all the power of the internet behind it.

XMLHttpRequest Object :

open(): establishes a new request to the server.

send(): Sends a request to the server.

abort(): Exits the current request.

readyState: Provides the ready state of the current HTML.

responseText: The request response text returned by the server.

Because of the browser wars of the previous two years, the XMLHttpRequest methods used by various browsers to get objects are different.

Supports multiple browsers to create XMLHttpRequest objects

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 that will be created.
2. Try to create the object in Microsoft browser:
Try to create it using the Msxml2.xmlhttp object.
If it fails, try microsoft.xmlhttp the object again.
3. If XmlHttp is still not established, the object is created in a non-Microsoft manner.
Finally, XmlHttp should refer to a valid XMLHttpRequest object, no matter what browser it runs.

Request/Response in Ajax

Make a request: the same process is basically the same in an Ajax application:
1. Get the data you want from the Web form.
2. Establish the URL to connect to.
3. Open the connection to the server.
4. Set the function to run after the server finishes.
5. Send the request.

function CallServer () {//Get the city and state from the web Formvar city = document.getElementById ("City"). Value;var STA Te = document.getElementById ("state"). value;//only go on if there is values for both fieldsif (city = null) | | (City = = "")) Return;if (state = = NULL) | | (state = = "")) return;//Build the URL to connect tovar url = "/scripts/getzipcode.aspx?city=" + Escape (city) + "&state=" + Escape (St ATE);//Open a connection to the Serverxmlhttp.open ("GET", url, true);//Setup a function for the server to run when it ' s Donexmlhttp.onreadystatechange = updatepage;//Send the requestxmlhttp.send (null);}


To Process the response :

ReadyState the value that may be returned:

0: The request was not initialized (not yet called open() ).

1: The request has been established but has not yet been sent (not yet called send() ).

2: The request has been sent, is in process (usually can now get the content header from the response).

3: The request is in process, and some of the data in the response is usually available, but the server has not finished generating the response.

4: The response is complete; you can get and use the server's response.

Must know two points:

1. Do nothing until xmlHttp.readyState the value of the property is equal to 4.

2. The server fills in the response into the xmlHttp.responseText attribute.


Response function:

function Updatepage () {  if (xmlhttp.readystate = = 4) {    var response = Xmlhttp.responsetext;    document.getElementById ("ZipCode"). Value = response;  }}


The starting code uses the basic JavaScript code to get the values of several form fields. Then set up an ASP script as the target of the link. To notice how the script URL is specified, city and state (from the form) are appended to the URL with a simple GET parameter.

Then open a connection, which is the first time you see the use XMLHttpRequest . It specifies the connection method (GET) and the URL to connect to. The last parameter, if set true , will request an asynchronous connection (this is the origin of Ajax). If used false , the code will wait for the response returned by the server after making a request. If set to true , the user can still use the form (or even call other JavaScript methods) when the server processes the request in the background.

xmlHttp(Remember, this is a XMLHttpRequest property of an object instance) that onreadystatechange tells the server what to do when it finishes running (it might take five minutes or five hours). Because the code does not wait for the server, you must let the server know what to do so that you can respond. In this example, if the server finishes processing the request, a special named updatePage() method is triggered.

Finally, a value null call is used send() . Since the data to be sent to the server has been added to the request URL (city and state), no data is sent in the request. This makes a request and the server works according to your requirements.

A simple summary of the work flow of Ajax:

JavaScript obtains the parameters or variables to pass to the server segment, and then uses the created XMLHttpRequest object to send a server segment, and if the server side accepts the data and returns the data, it is saved in the ResponseText property. Finally, the DOM is modified via JavaScript, which allows the client to modify data without flushing.

Reference:http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html


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.