Five years ago, if you don't know XML, you are a ugly ducklings who are not paid. 18 months ago, Ruby became the center of concern, I don't know if Ruby's programmer can only sit on the cold bench. Today, if you want to keep up with the latest technology, then your goal is AJAX.
However, Ajax is more than just a fashion, but it is a powerful way to build websites, and it is not as difficult as learning a new language.
But before explaining what is Ajax, let's take a few minutes to learn what Ajax is doing. Currently, there are two basic options when writing applications:
Desktop application web application
Both are similar, desktop applications typically use CD as media (sometimes downloadable from the website) and completely installed on your computer. Desktop applications may use the Internet to download updates, but run the code for these applications on the desktop computer. The web application runs on a Web server in somewhere - it is not surprising, to access this application through a web browser.
However, what is more important than the running code of these applications is how the application runs and how to interact with it. Desktop applications are usually very fast (just on your computer, do not wait for internet connection), with beautiful user interfaces (usually related to operating systems) and extraordinary dynamics. You can click, select, Enter, open the menu and submenu, you can patrol it everywhere, basically no waiting.
On the other hand, the web application is the latest trend, which provides services that cannot be implemented on the desktop (such as Amazon.com and eBay). However, accompanying the power of the Web is waiting, waiting for the server response, waiting screen refresh, wait for the request to return and generate a new page.
Obviously this is too simple, but the basic concept is. You may have guess that Ajax attempts to establish the functionality and interactivity of desktop applications, with bridges between the Updated web applications. You can use dynamic user interfaces and beautiful controls like desktop applications, just in the web application.
What are you waiting for? Let's take a look at how Ajax transforms the clumsy web interface into the Ajax application that can quickly respond quickly.
Old technology, new skill
When talking about Ajax, it is actually involved in a variety of technologies, and it is necessary to flexibly use it necessary to understand these different technologies (including the first few articles of this series will discuss these technologies respectively). Good news is that you may be very familiar with most of them, and better is that these technologies are easy to learn, not as difficult as a complete programming language (such as Java or Ruby).
Ajax's definition is in the way, Ajax is an abbreviation for Asynchronous JavaScript and XML (and DHTML, etc.). This phrase is Adaptive Path's Jesse James Garrett invented (see Resources), follows Jesse explanation, this is not a first letter abbreviation.
Below is the basic technique used by the Ajax application:
HTML is used to establish a web form and determine the fields used in other parts of the application. JavaScript code is the core code of running the AJAX application to help improve communication with the server application. DHTML or Dynamic HTML for dynamic update forms. We will use DIV, SPAN, and other dynamic HTML elements to mark HTML. Document Object Model DOM is used to handle the HTML structure and (in some cases) the XML returned by the HTML structure and (in some cases). Let's further analyze the responsibilities of these technologies. In the future article, I will discuss these technologies in the future, as long as they are familiar with these components and technologies. The more familiar with these code, the easier, easily transforming the zeroing of these technologies to truly grasp these techniques (and also truly open the gate of Web application development).
XMLHttpRequest object
An object to be understood may be the most strange to you, namely XMLHttpRequest. This is a JavaScript object that creates this object is simple, as shown in Listing 1.
Listing 1. Creating a new XMLHttpRequest object
VAR Xmlhttp = new xmlhttpRequest ();
script>
This object will be discussed further in the next article, and now you have to know that this is an object that handles all servers. Before you continue to read, stop and think about it: Dialogue with the server through the XMLHttpRequest object is JavaScript technology. This is not a general application stream, which is precisely the source of the power of AJAX.
In a general web application, the user fills in the form field and click the Submit button. The entire form is then sent to the server, and the server forwards it to the script of the processing form (usually PHP or Java, may also be a CGI process or something similar), and then send back to a new page after the script is executed. This page may be an HTML with a new form that has already populated some data, or it may be a confirmation page, or a page with some options to select in the original form. Of course, the user must wait when the script or program processing on the server and returns a new form. The screen becomes a blank, wait until the server returns the data and then resemble it. This is the reason why the interaction is poor, and the user does not feedback immediately, so it feels different from the desktop application.
Ajax is basically the JavaScript technology and XMLHttpRequest objects between web forms and servers. When the user fills in the form, the data is sent to some JavaScript code instead of being sent to the server. Instead, JavaScript code captures form data and sends a request to the server. At the same time, the form on the user screen will not flash, disappear or delayed. In other words, the JavaScript code sends a request behind the scenes, and the user does not even know the request. Better, the request is asynchronous, that is, JavaScript code (and users) does not have to wait for the server response. So users can continue to enter data, scroll screens, and use applications.
Then, the server returns the data (still in the web form), the latter determines how to handle this data. It can quickly update form data, which makes people feel that the application is complete immediately, and the form is not submitted or refreshed and the user gets new data. JavaScript code can even perform some calculation on the received data, then send another request, do not need user intervention! This is the power of XMLHttpRequest. It can interact with the server as needed, and users can even do everything that occurs after the scene. The result is similar to the dynamic, fast response, high interaction experience of desktop applications, but there is a strong force behind the Internet. Add some JavaScript
After getting the handle of XMLHTTPREQUEST, the other JavaScript code is very simple. In fact, we will use the JavaScript code to complete very basic tasks:
Get Form Data: JavaScript code is easy to extract data from the HTML form and send it to the server. Modify the data on your form: Update form is also very simple, from setting field value to quickly replace the image. Analyze HTML and XML: Manipulate the DOM using JavaScript code (see the next section), process the structure of the XML data returned by the HTML form server.
For the top two, it is necessary to be very familiar with the getElementById () method, as shown in Listing 2.
Listing 2. Capting and setting field values with JavaScript code
// Get the value of the "phone" Field and Stuff It in a variable called phone
Var phone = document.getlementByid ("Phone"). Value;
// set Some VALUES ON A FORM USING AN Array Called Response
Document.getElementByid ("Order"). Value = response [0];
Document.getlementByid ("Address"). Value = response [1];
There is no particular attention to it, it is really good! You should recognize that there is no very complicated thing here. As long as the XMLHttpRequest is mastered, the other parts of the Ajax application is the simple JavaScript code shown in Listing 2, and there is a small amount of HTML. At the same time, we have to use a little DOM, let's take a look.
End with DOM
Finally, there is a DOM, ie the document object model. It may be a little bit of a child, and HTML designers use it, even if JavaScript programmers are not used, unless a high-end programming task is to be completed. A large number of DOMs are complex Java and C / C programs, which may be that DOM is considered to be difficult to learn.
Fortunately, it is easy to use DOM in JavaScript technology. It is also very intuitive. Now, in accordance with regular perhaps, you should show how to use DOM, or at least some sample code, but you may mislead you. Even if you don't pay attention to DOM, you can still discuss AJAX, which is also the method I prepared. The subsequent article will discuss DOM again, and now you know that you may need DOM. When we need to pass XML and change the HTML form between JavaScript code and the server, we will further study the DOM. Don't do some interesting work, so put the DOM on one side. Get a request object
With the basic knowledge above, let's take a look at some specific examples. XmlhttpRequest is the core of the Ajax application, and it may be more unfamiliar with many readers. We will start here. As you can see from Listing 1, it is very simple to create and use this object, isn't it? Wait a minute.
Remember those nasty browser wars a few years ago? There is no such thing as the same result on different browsers. Regardless of whether you believe, these wars continue, although the scale is small. But strangely, XMLHttpRequest became one of the victims of this war. Therefore, you may need to use different methods. Below I will explain in detail.
Use Microsoft Browser
Microsoft Browser Internet Explorer uses the MSXML parser to process XML (you can further understand MSXML by reference). So if you have written the AJAX application to deal with Internet Explorer, you must create an object in a special way.
But not that simple. According to the JavaScript technology version installed in Internet Explorer, MSXML actually has two different versions, so the code must be written separately. See Listing 3, where the code creates an XMLHttpRequest on the Microsoft browser.
Listing 3. Creating an XMLHttpRequest object on a Microsoft browser
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 these code, but there is no relationship. When this series is over, you will have a deeper understanding of JavaScript programming, error handling, conditional compilation, etc. Now just keep in keeping in two lines of code:
XMLHTTP = New ActiveXObject ("msxml2.xmlhttp");
with
XMLHTTP = New ActiveXObject ("Microsoft.xmlhttp") ;.
These two lines of code are basically trying to create an object using a version of MSXML, and if it fails, use another version to create the object. Not bad right? If it is not successful, set the XMLHTTP variable to false and tell your code. If this happens, it may be because of the installed non-Microsoft browser, you need to use different code.
Handling Mozilla and non-Microsoft browser
If the selected browser is not Internet Explorer, or writing code for non-Microsoft browsers, you need to use different code. In fact, a simple code shown in Listing 1: VAR XMLHTTP = New XMLHTTPREQUEST OBJECT ;.
This line is a simple code in Mozilla, Firefox, Safari, Opera, and all non-Microsoft browsers that support AJAX in any form or mode, create an XMLHttpRequest object.
Combined
The key is to support all browsers. Who is willing to write a application that can only be used for Internet Explorer or non-Microsoft browser? Or worse, to write a application twice? of course not! So the code should support Internet Explorer and non-Microsoft browsers. Listing 4 shows such a code.
Listing 4. Creating an XMLHttpRequest object in a way to support a variety of browsers
/ * 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 no matter what the strange symbols that comments, such as @cc_on, this is a special JavaScript compiler command, which will be discussed in detail in the next issue of XMLHttpRequest. The core of this code is three steps:
Create a variable XMLHTTP to reference the upcoming XMLHttpRequest object. Try to create the object in the Microsoft browser:
Try to create it with the MSXML2.xmlhttp object. If you fail, try Microsoft.xmlhttp objects. If you still have XMLHTTP, you will create this object in a non-Microsoft.
Finally, XMLHTTP should reference an effective XMLHttpRequest object, no matter what kind of browser runs.
One point of security
What is safety? Now the browser allows users to improve their security level, close JavaScript technology, disable any options in the browser. In this case, the code will not work anyway. At this point, problems must be handled appropriately, which requires a separate article to discuss, put it later (this series is long enough? Don't worry, you may master it before reading it). Now we have to write a strong but not enough perfect code, it is fine for the master of Ajax. We will also discuss more details.
Request / Response in the Ajax World
Now we introduce AJAX, which has a basic understanding of the XMLHttpRequest object and how it creates it. If you read very carefully, you may already know that JavaScript technology is also known as the web application on the server, not directly to the HTML form for that application. What is missing? How to use XMLHttpRequest. Because this code is very important, you have written every Ajax application to use it in some form, first look at what Ajax's basic request / response model is like.
Request a request
You already have a brand new XMLHttpRequest object, now let it do yourself. First, a JavaScript method that is required to be called (such as when a user enters text or selecting one from the menu). The next step is the process that is basically similar in all AJAX applications:
Get the required data from the web form. Establish the URL to connect. Open to the server. Set the function to run after the server is complete. send request.
The example AJAX method in Listing 5 is organized in this order:
Listing 5. Send a AJAX request
Function Call Server () {
// Get the city and state from the web form
Var city = document.getlementByid ("city"). value;
Var State = Document.GtelementByid ("state"). Value;
@ On on 帖子 帖子 帖子
IF ((City == Null) | (City == ")) Return;
IF (state == null) | (state == ")) Return;
// build the url to connect to
VAR URL = "/scripts/getzipcode.php?city=" escape (city) "& statin =" 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 meanings are clear. The starting code uses the basic JavaScript code to get the value of several form fields. Then set a PHP script as the target of the link. Pay attention to the specified mode of the script URL, CITY and STATE (from form) are attached to the URL using a simple GET parameter.
Then open a connection, this is the first time you see using XMLHttpRequest. The connection method (GET) and the URL to be connected are specified. If the last parameter is set to true, then a asynchronous connection is requested (this is the origin of Ajax). If you use false, then the code will be returned after the request will be returned. If set to True, the user can still use the form when the server is processed in the background, and even calls other JavaScript methods.
XMLHTTP (Remember, this is the onReadyStateChange property of the XMLHttpRequest object) can tell the server after the operation is complete (maybe five minutes or five hours). Because the code does not wait for the server, you must let the server know how to do so you can respond. In this example, if the server processes the request, a special method called UpdatePage () will be triggered. Finally, use a value NULL to call Send (). Since the data to be sent to the server has been added to the request URL, no data is required in the request. This issues a request, and the server works in accordance with your requirements.
If you don't find any fresh things, you should experience how easy it is! In addition to firmly remembering the asynchronous features of AJAX, these content is quite simple. I should grateful Ajax allows you to focus on pretty 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 simple text, which can be used as part of the request URL. Send a request with GET instead of more complex POST. Without XML and the content header to add, there is no data to be sent in the request body; in other words, this is the Utopia of Ajax.
Don't worry, with this series of articles, things will become more complicated. You will see how to send a POST request, how to set the request header and content type, how to encode XML in the message, how to increase the security of the request, there is still a lot of work that can be done! You don't have to manage those difficulties in the time being, master the basic things, soon we will establish a complete set of Ajax tool libraries.
Processing response
Now face the response of the server. Now just know two points:
Don't do anything until the value of the XMLHTTP.ReadyState property is equal to 4. The server will populate the response into the XMLHTTP.ResponseText property.
The first point, ready state, will discuss in detail in the next article, you will learn more about the phase of the HTTP request, which may be more than you think. Now you can check a specific value (4) (there is more value in the next article to introduce). Second, use the XMLHTTP.ResponseText attribute to get the server's response, which is simple. The example method in Listing 6 can be called by the server according to the data transmitted in Listing 5.
Listing 6. Processing server response
Function updatePage () {
IF (xmlhttp.readyState == 4) {
Var response = xmlhttp.responsext;
Document.getElementByid ("zipcode"). Value = response;
}
}
These codes are also not difficult. It waits for the server call. If it is ready, use the value returned by the server (here is the user entered into the city and the ZIP code) to set the value of another form field. The zipcode field containing the ZIP encoded suddenly appeared, and the user did not press any button! This is the feeling of the desktop app mentioned earlier. Quick response, dynamic feelings, etc. These are just because there is a small Ajax code.
Careful readers may notice that zipcode is a normal text field. Once the server returns the zip encoding, the UpdatePage () method sets the value of the field with the city / state ZIP encoding, and the user can override the value. There are two reasons why this: maintain an example, indicating that the user may want the user to modify the data returned by the server. To remember these two points, they are important for good user interface design. Connect web form
What else? It is actually not much. A JavaScript method captures the information of the user into the form and sends it to the server, another JavaScript method to listen to and process responses, and set the value of the field when the response is returned. All of this actually relies on calling the first JavaScript method, which launches the entire process. The most obvious way is to add a button in the HTML form, but this is the 2001 approach, do you think so? Also using JavaScript technology like Listing 7.
Listing 7. Start an AJAX process