AJAX Introduction and Getting Started example _ajax related

Source: Internet
Author: User
Tags html form http request object model php script response code advantage

Ajax technology is complex and esoteric for a novice like me who has just come in contact with web development and has little real-world experience. After two days of Baidu, Google, I have a general understanding of the fundamentals of Ajax, in this summary.

1. What is Ajax?
The Ajax full name is asynchronous JavaScript and XML, an abbreviation for asynchronous JavaScript and XML. Ajax technology is used to create Web sites for interactive Web applications, and for what is asynchronous, the text will be interpreted later.

1.1 Desktop applications and Web applications
Before discussing Ajax techniques in detail, you need to know exactly what Ajax technology is for. Currently, there are two basic types of authoring applications:

Desktop Applications (Desktop application)
Web application (Web application)
Desktop applications can be obtained from the Internet or by CD, and need to be run on desktop computers, such as some of our common PC software. Unlike Web applications, Web applications run on a Web server somewhere, so they need to be accessed through a Web browser.

However, more important than where the code of these applications are running is how the application works and how it interacts with it. Desktop applications are generally faster and have a nice user interface and extraordinary dynamics, you can click, select, open menus and submenus, cruise around, and do not have to wait; on the other hand, Web applications, such as Amazon.com and ebay, provide services that desktop programs cannot achieve. However, as the web is strong, waiting waits, waits for the server to respond, waits for the screen to refresh, waits for the request to return and produces the new interface.

The advent of Ajax is to mitigate the problem of waiting in Web applications compared to desktop applications.

1.2 AJAX-old technology, new faces
Ajax technology is not really a new technology, but the integration of several other existing technologies.

AJAX applications use the following basic techniques:

Use HTML and CSS to create Web Forms and represent web page information;
Use JavaScript to manipulate Dom (Document Object Model) for dynamic display and interaction;
Asynchronous data exchange with the Web server using the XMLHttpRequest object;
Use XML for data exchange and related operations;
Use JavaScript to bind everything together.
We are here to further analyze the responsibilities of these technologies. Now I just need to familiarize myself with these components and technologies. The more familiar these codes are, the easier it is to move from a fragmented understanding of these technologies to a real grasp of those technologies (and also really open the door to WEB application development).

XMLHttpRequest Objects

One of the objects you want to know is probably the most unfamiliar to you, XMLHttpRequest. This is a JavaScript object, and creating the object is simple, as shown in Listing 1.

Listing 1. Create a new XMLHttpRequest object

Copy Code code as follows:

<script language= "javascript" type= "Text/javascript" >
<!--
var xmlHttp = new XMLHttpRequest ();
-->
</script>

You'll learn more about this object later, and now you know that this is the object that handles all server traffic. Before you go on, stop and think: The JavaScript technology is a conversation with the server through the XMLHttpRequest object. This is not a generic application flow, which is precisely the source of the powerful functionality of Ajax.
In a typical WEB application, users fill Out form fields and click the Submit button. The entire form is then sent to the server, and the server forwards it to the script that handles the form (usually PHP or Java, or maybe a CGI process or something like that), and then sends it back to the new page after the execution of the script completes. The page may be HTML with a new form that has already populated some data, a confirmation page, or a page that has some options selected based on the input data from the original form. Of course, users must wait when a script or program on the server processes and returns a new form. The screen becomes blank until the server returns data and then redraw it. 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, JavaScript code sends a request behind the scenes, and the user doesn't even know the request is sent. Better yet, requests are sent asynchronously, meaning that JavaScript code (and users) does not have to wait for a response from the server. 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 to process the data. It can quickly update form data, making people feel that the application is done immediately, the form is not submitted or refreshed, and the user gets the new data. JavaScript code can even perform some sort of calculation on the received data, and then send another request without user intervention at all! This is the strength of XMLHttpRequest. It can interact with the server on its own, and users may even have no idea what's going on behind the scenes. The result is a dynamic, fast-response, highly interactive experience similar to desktop applications, but with all the power of the internet behind it.
Add some JavaScript
After you get the XMLHttpRequest handle, the other JavaScript code is very simple. In fact, we'll use JavaScript code to do very basic tasks:

Get form data: JavaScript code can easily extract data from an HTML form and send it to the server.
Modifying data on a form: it is also easy to update a form, such as setting a field value or quickly replacing an image.
Parsing HTML and XML: Manipulating the DOM using JavaScript code to handle the structure of the XML data returned by the HTML form server.
For the first two points, you need to be very familiar with the getElementById () method, as shown in Listing 2.

Listing 2. Capturing and setting field values with JavaScript code
Copy Code code as follows:

Get the value of the ' phone ' field and stuff it in a variable called phone
var phone = document.getElementById ("Phone"). Value;
Set Some values on a form using an array called response
document.getElementById ("Order"). Value = Response[0];
document.getElementById ("Address"). Value = Response[1];

There is no particular place to watch, it's great! You should realize that there is nothing very complicated here. Just master the rest of the Xmlhttprequest,ajax application is the simple JavaScript code shown in Listing 2, mixed with a small amount of HTML.

2. What are the advantages and disadvantages of Ajax?
The advantages of 2.1 Ajax
The biggest advantage of using AJAX is the ability to maintain data without updating the entire page. This enables Web applications to respond more quickly to user requests, while improving the user experience while avoiding the sending of information that has not changed over the network.

Traditional Web applications allow the user to fill out forms (form) and send a request to the Web server when a form is sent. The server receives and processes the form and sends it back to a new Web page, but this practice wastes a lot of bandwidth because: most of the HTML code is the same in the two-post-feedback page rollup. Because each application communication needs to send a request to the server, the application response time depends on the response time of the server, which causes the user interface response is much slower than the native application.

In contrast, AJAX applications can only send and retrieve the necessary data to the server, using SOAP or some other Xml-based page service Interface (interface), and using JavaScript to handle the response from the server on the client. Because the amount of data exchanged between the server and the browser is substantially reduced (about 5% of the original), we can see that the response (server response) is quicker to apply (results). At the same time, a lot of processing work can be done on the requesting client machine, so the Web server has less processing time.

Disadvantages of 2.2 Ajax
The main criticism for Ajax is that it can disrupt the normal behavior of the browser's Back button. When the page is dynamically updated, the user cannot go back to the previous page because the browser can only record static pages in the history. The difference between a fully read page and a page that has been dynamically modified is subtle: Users usually want to click the Back button to cancel their previous operation, but they may not be able to do so in an AJAX page. But developers have come up with ways to solve the problem, most of which are to reproduce changes on the page by creating or using a hidden iframe when the user clicks the Back button to access the history. (for example, when a user clicks back in Google Maps, it searches in a hidden iframe and then reflects the search results onto AJAX elements to restore the application state to its current state.) )

Another relevant view is that using dynamic page updates makes it difficult for a user to save a particular state to a favorite folder. The solution to this problem has also emerged, mostly using a URL fragment identifier (usually called an anchor point, the part behind the # in the URL) to keep track and allow the user to return to a specified application state. (many browsers allow JavaScript to dynamically update anchor points, which enables AJAX applications to update the anchor points while updating the display content.) This solution also solves many arguments about not supporting the back button.

During AJAX development, network latency-the interval between a user making a request and a response from the server-requires careful consideration. Not to give users a clear response, no proper read data, or improper handling of XMLHttpRequest, will cause users to feel the delay, which users do not want to see, but also they can not understand. The usual solution is to use a visual component to tell the user that the system is in the background and is reading the data and content.

3. Common process for AJAX applications
3.1 Creating the Request object
With the basics above, let's take a look at some concrete examples. XMLHttpRequest is the core of AJAX applications and may be unfamiliar to many readers, so let's start here. As you can see from listing 1, creating and using this object is very simple, isn't it? Wait a minute.

Remember those pesky browser wars a couple of years ago? There is no such thing as a different browser to get the same result. Whether you believe it or not, these wars are still going on, albeit on a smaller scale. Regrettably, however, XMLHttpRequest became one of the victims of this war. So getting XMLHttpRequest objects may require a different approach. I'll explain it in detail below.

using Microsoft browser

Microsoft Browser Internet Explorer uses the MSXML parser to work with XML. So if you are writing an AJAX application that is dealing with Internet Explorer, you must create the object in a special way.

But it's not that simple. Depending on the version of JavaScript technology installed in Internet Explorer, MSXML actually has two different versions, so you must write code for each of these two situations. See listing 3, where the code creates a xmlhttprequest on a Microsoft browser.

Listing 3. Create a XMLHttpRequest object on a Microsoft browser
Copy Code code as follows:

var xmlHttp = false;
try {
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E2) {
XmlHttp = false;
}
}

You may not fully understand the code, but it doesn't matter, so just keep in mind the two lines of code:

XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");

These two lines of code are basically trying to create an object using one version of MSXML, and if it fails, create the object with a different version. Nice, huh? If none succeeds, set the xmlHttp variable to False to tell you that there is a problem with your code. If this happens, it may be that a non-Microsoft browser is installed and you need to use different code.

working with Mozilla and non-Microsoft browsers

If you choose a browser other than Internet Explorer, or you write code for a non-Microsoft browser, you need to use different code. In fact, this is the simple line of code shown in Listing 1:

var xmlHttp = new XMLHttpRequest object;.

This much simpler code creates the XMLHttpRequest object in Mozilla, Firefox, Safari, Opera, and virtually all non-Microsoft browsers that support Ajax in any form or mode.

A common way to integrate across browsers

The key is to support all browsers. Who wants to write an application that can only be used for Internet Explorer or non-Microsoft browsers? Or worse, write an application two times? Of course not! Therefore, the code should support both Internet Explorer and non-Microsoft browsers. Listing 4 shows such a code.

Listing 4. Create a XMLHttpRequest object in a way that supports multiple browsers
Copy Code code as follows:

/* Create A new XMLHttpRequest object to talk to the WEB server * *
var xmlHttp = false;
/* @cc_on @*/
/* @if (@_jscript_version >= 5)
try {
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E2) {
XmlHttp = false;
}
}
@end @*/
if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {
XmlHttp = new XMLHttpRequest ();
}

Now, regardless of the strange notations that are commented out, such as @cc_on, this is a special JavaScript compiler command that will be discussed in detail in the next installment of the article for XMLHttpRequest. The core of this piece of code is divided into three steps:

Establish a variable xmlHttp to reference the XMLHttpRequest object that is about to be created.
Try creating the object in a Microsoft browser:
Try to create it using the Msxml2.xmlhttp object.
If it fails, try microsoft.xmlhttp the object again.
If XmlHttp is still not established, the object is created in a non-Microsoft way.
Finally, XmlHttp should refer to a valid XMLHttpRequest object, no matter what browser is running.

a client request/server Response Mechanism 3.2 AJAX Technology
Now that we've covered Ajax, we have a basic understanding of the XMLHttpRequest object and how to create it. If you read carefully, you may already know that JavaScript technology is dealing with WEB applications on the server, rather than HTML forms that are submitted directly to that application.

What else is missing? How to use XMLHttpRequest in the end. Because this code is very important, every AJAX application you write will have to use it in some way, first look at the basic AJAX request/response model.

making a request

You've got a brand-new XMLHttpRequest object, now let it do something. First you need a JavaScript method that a Web page can invoke (for example, when the user enters text or selects an item from the menu). The next step is a process that is basically identical in all Ajax applications:

Get the data you need from a Web form.
Establishes the URL to connect to.
Open the connection to the server.
Sets the function to run when the server completes.
Send the request.
The example Ajax method in Listing 5 is organized in this order:

Listing 5. Making an Ajax request
Copy Code code as follows:

function CallServer () {
Get the "city" and state from the Web Form
var city = document.getElementById ("City"). Value;
var state = document.getElementById (' state '). Value;
Only go in if there are values for both fields
if (city = null) | | (City = = "")) Return
if ((state = null) | | (state = = "")) Return
Build the URL to connect to
var url = "/scripts/getzipcode.php?city=" + Escape (city) + "&state=" + Escape (state);
Open a connection to the server
Xmlhttp.open ("Get", url, True);
Setup a function for the "server to run" when it's done
Xmlhttp.onreadystatechange = Updatepage;
Send the request
Xmlhttp.send (NULL);
}

Most of the code has a clear meaning. The starting code obtains the values of several form fields using basic JavaScript code. Then set a PHP script as the target of the link. Notice how the script URL is specified, and 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 Using XMLHttpRequest. The connection method (get) and the URL to connect are specified. If the last argument is set to True, an asynchronous connection will be requested (this is the origin of Ajax). If you use False, the code will wait for the response returned by the server after it makes a request. If set to True, the user can still use the form (or even invoke other JavaScript methods) when the server is processing the request in the background.

XmlHttp (Remember, this is the XMLHttpRequest object instance) onReadyStateChange property tells the server what to do after the run 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 what to do so that you can respond. In this example, if the server has finished processing the request, a special method named Updatepage () will be triggered.

Finally, use the value NULL to call Send (). Because the data to be sent to the server (city and state) has been added to the request URL, no data needs to be sent in the request. This makes the request, and the server works according to your requirements.

If you don't find anything new, you should realize how simple and clear it is! In addition to remembering the asynchronous nature of Ajax, these things are fairly straightforward. It should be appreciated that Ajax allows you to concentrate on writing beautiful applications and interfaces without worrying about complex HTTP request/response code.

The code in Listing 5 illustrates the ease of use of Ajax. The data is a simple text that can be used as part of the request URL. Send a request with a get instead of a more complex POST. There is no XML and the header to add, there is no data to send in the request body, in other words, this is the utopia of Ajax.

Don't worry, things will get more and more complicated as this series of articles unfolds. You'll see how to send POST requests, how to set request headers and content types, how to encode XML in messages, how to increase the security of your request, and there's a lot more you can do! For the time being, you don't have to take care of the difficult points, just master the basics and soon we'll build a whole suite of Ajax tools.

Handling Responses

Now you have to face the server response. Now just know two points:

Do nothing until the value of the Xmlhttp.readystate property equals 4.
The server populates the Xmlhttp.responsetext property with the response.
The 1th, ready state, will be discussed in more detail in the next article, and you will learn more about the HTTP request phase than you might have imagined. Now it's OK to just check a specific value (4) (There are more values to introduce in the next installment). 2nd, using the Xmlhttp.responsetext property to get the server's response is simple. The example method in Listing 6 is available for the server to call based on the data that is sent in Listing 5.

listing 6. Processing server Responses
Copy Code code as follows:

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

The code is also neither difficult nor complex. It waits for the server to invoke and, if it is ready, sets the value of another form field using the value returned by the server (here is the ZIP encoding of the city and state that the user entered). The ZipCode field that contains the ZIP code suddenly appears, and the user does not press any buttons! This is what the desktop application feels like before. Quick response, dynamic feeling, and so on, all because of a little bit of Ajax code.

Attentive readers may notice that ZipCode is an ordinary text field. Once the server returns a ZIP code, the Updatepage () method sets the value of that field with the city/State zip code, and the user can overwrite the value. There are two reasons for doing this: keeping the example simple means that you may sometimes want users to be able to modify the data returned by the server. To keep these two points in mind, they are important for good user interface design.


3.3 [out of question] how to connect to a Web Form
What else is there? Actually, not much. A JavaScript method captures the user's input form information and sends it to the server, and another JavaScript method listens and processes the response and sets the value of the field when the response is returned. All of this actually relies on invoking the first JavaScript method, which starts the entire process. The most obvious way is to add a button to the HTML form, but this is the 2001 approach, don't you think? Or use JavaScript technology like Listing 7.

Listing 7. Start an Ajax process
Copy Code code as follows:

<form>
<p>city: <input type= "text" name= "City" id= "City" size= "25"
Onchange= "CallServer ();"/>
<p>state: <input type= "text" name= "state" id= "state" size= "25"
Onchange= "CallServer ();"/>
<p>zip Code: <input type= "text" name= "ZipCode" id= "City" size= "5"/>
</form>

If it feels like a fairly common code, that's right, that's it! When a user enters a new value in the City or state field, the CallServer () method is triggered, and Ajax begins to run. Do you understand what's going on? Well, that's it!

4. What are the problems facing the development of AJAX applications?
For programmers, the headaches of developing AJAX applications are the following:

Ajax is essentially a browser-side technology, first of all facing the inevitable first problem is browser compatibility issues. There is always some javascript/dom/css or bugs in the support of each browser, and even the support for javascript/dom/css between versions of the same browser may be partially different. This causes programmers to spend most of their time writing AJAX applications debugging browser compatibility rather than the application itself.
The main purpose of Ajax technology is to partially exchange data between client and server. As with the traditional master-slave architecture, it is inevitable that part of the business logic will be implemented at the client, or partly in the client section on the server. Because business logic may be dispersed between the client and the server and implemented in different programming languages, this makes Ajax applications extremely difficult to maintain. If there is a user interface or business logic change requirements, coupled with the previous JAVASCRIPT/DOM/CSS compatibility issues, AJAX applications often become a programmer's nightmare. For business logic decentralization, the AJAX development framework can be broadly divided into two categories:
The business logic and presentation layer are placed in the browser, and the data layer is placed on the server: Because all programs execute JavaScript on the client side, they are required to serve the server only when data is needed, which is also known as the Fat Client (FAT) architecture. The server is typically used only to provide and store data under this architecture. The advantage of this method is that the programmer can use JavaScript with business logic to make a special user interface to meet the requirements of the end user. But there's a lot of problems, because in the first, the ability of the JavaScript language itself may not be enough to handle complex business logic. Second, the performance of JavaScript has always been poor. Third, JavaScript access to server data, still need appropriate server-side program to match. Finally, the problem of browser compatibility appears again. Some AJAX development frameworks such as DWR attempt to avoid compatibility problems by automatically generating JavaScript, and opening channels enable JavaScript to directly invoke server-side Java programs to simplify data access. But the first and 22 questions remain, and programmers have to pay a considerable amount of effort to reach the specifications of the application, or they may not be able to meet the requirements at all.
The presentation layer, business logic, and data tier are placed on the server, and the browser has only the user interface engine (Interface engine), which is also called the Thin client (thin client) architecture, or the hub server (server-centric) architecture. The browser's user interface engine is used only to reflect the performance layer of the server and to convey the user's input back to the server's presentation layer. Events triggered by the browser are also sent back to the server for processing, updating the presentation layer based on business logic, and then reflecting back to the browser. Because all applications are implemented entirely on the server, data and presentation layers are directly accessible, programmers need to use a relatively mature server-side programming language (such as the Java language), and it is relatively easy to develop applications without learning javascript/dom/css. The disadvantage is that the user interface engine and the presentation layer usually exist in the form of standard components, such as the need for special components (user interfaces), often to be provided by the developer of the original framework, slow. such as the open source Code AJAX development Framework ZK currently supports XUL and XHTML components, there is no XAML support.
Ajax is an asynchronous way of submitting requirements to the server. For the server, it is not different from the traditional submission form requirements, and because it is committed asynchronously, if there are multiple Ajax requirements and form submission requirements, it will be impossible to ensure which requirements first get the server response. This can result in a typical multi process (processes) or multithreaded (thread) competition (racing) problem for an application. Programmers have to deal with it or do it in JavaScript to avoid such competitive problems (such as disable the button before the AJAX requirements are not answered), which unnecessarily increases the burden on the programmer. The development framework known to automate this issue now seems to be only ZK.

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.