By Brett McLaughlin
Most Web ApplicationsProgramAll use the request/Response Model to obtain the complete HTML page from the server. It is often a process of repeatedly clicking a button, waiting for the server to respond, then clicking another button, and then waiting. With Ajax and XMLHttpRequest objects, you can use the request/response model that does not have users waiting for server response. In this article, Brett McLaughlin describes how to create XMLHttpRequest instances that adapt to different browsers, create and send requests, and respond to servers.
In this article, you will begin to access all the basic and basic Ajax objects and programming methods: XMLHttpRequest objects. This object is actually a public thread that spans all Ajax applications. As you may have expected, only a thorough understanding of this object can give full play to the potential of programming. In fact, you may find that XMLHttpRequest cannot be used to correctly use XMLHttpRequest. What the hell is going on?
Web 2.0 glance
In-depth researchCodeFirst, let's take a look at our recent point of view. We must be very clear about the concept of Web 2.0. When you hear the word Web 2.0, you should first ask "What is Web 1.0 ?" Although few people mentioned web 1.0, it actually refers to the traditional web with completely different request and response models. For example, click a button on the Amazon.com website or enter a search item. Then a request is sent to the server, and the response is returned to the browser. This request is not only a list of books and bibliography, but also a complete HTML page. Therefore, when a web browser redraws an HTML page with a new one, it may see flashes or jitters. In fact, the request and response are clearly displayed on each new page.
Web 2.0 (to a large extent) eliminates this visible reciprocating interaction. For example, visit websites such as Google maps or Flickr (for links to these websites that support Web 2.0 and Ajax, see references ). For example, on Google Maps, you can drag a map, zoom in and out, with only a few repainting operations. Of course, there are still requests and responses, but they are all hidden behind the scenes. As a user, the experience is more comfortable and feels like a desktop application. This new feeling and pattern is what you feel when someone mentions Web 2.0.
You need to be concerned about how to make these new interactions possible. Obviously, requests and responses still need to be sent, but it is the HTML re-painting of each request/response interaction that results in a slow and clumsy web interaction. Therefore, it is clear that we need a method to make the sent request and received response only contain the required data, rather than the entire HTML page. The only time you need to get the entire HTML page is when you want the user to see the new page.
However, most interactions include adding details, modifying the subject text, or overwriting the original data on an existing page. In these cases, the Ajax and Web 2.0 methods allow sending and receiving data without updating the entire HTML page. For those who frequently access the Internet, this capability can make your applications feel faster and respond more timely, so that they can patronize your website from time to time.
Introduction to XMLHttpRequest
To realize such a brilliant miracle, you must be very familiar with a JavaScript Object, XMLHttpRequest. This small object has actually existed in several browsers for a while. It is the core of Web 2.0, Ajax, and most other content to be introduced in the next few months of this column. To help you quickly understand the object in a large scale, the following describes a few methods and attributes that will be used for this object.
· Open (): Create a new request to the server.
· Send (): send a request to the server.
· Abort (): exit the current request.
· Readystate: Provides the ready status of the current HTML.
· Responsetext: Request Response text returned by the server.
If you do not know this (or any of them), you don't have to worry about it.ArticleDescribes each method and attribute. Now we should understand what to do with XMLHttpRequest. Note that these methods and attributes are related to sending requests and processing responses. In fact, if you see all the methods and attributes of XMLHttpRequest, you will find that they are related to a very simple request/response model. Obviously, we will not encounter a very new GUI object or a super mysterious method for creating user interaction. We will use very simple requests and very simple responses. It does not seem attractive, but using this object can completely change your application.
Simple new
Create a new variable and assign it an XMLHTTPRequest object instance. This is simple in Javascript. You only need to use the new keyword for the object name, as shown in Listing 1.
Listing 1. Creating a New XMLHTTPRequest object
<Script language = "JavaScript" type = "text/JavaScript"> VaR request = new XMLHttpRequest (); </SCRIPT> |
Not hard? Remember, JavaScript does not need to specify the variable type, so it does not need to be done as in Listing 2 (this may be required in Java ).
Listing 2. Creating Java pseudocode for XMLHttpRequest
XMLHttpRequest request = new XMLHttpRequest (); |
Therefore, create a variable in Javascript using VAR, give it a name (such as "request"), and then assign it a new XMLHttpRequest instance. Then you can use this object in the function.
Error Handling
In fact, all kinds of things may go wrong, and the above Code does not provide any error handling. A better way is to create this object and exit gracefully when a problem occurs. For example, any earlier browser (whether or not you believe that someone is still using the old version of Netscape Navigator) does not support XMLHttpRequest. You need to let these users know that something is wrong. Listing 3 describes how to create an object so that a javascript warning is triggered when a problem occurs.
Listing 3. Creating XMLHttpRequest with error processing capability
<Script language = "JavaScript" type = "text/JavaScript"> VaR request = false; Try { Request = new XMLHttpRequest (); } Catch (failed ){ Request = false; }If (! Request) Alert ("error initializing XMLHttpRequest! "); </SCRIPT> |
Be sure to understand these steps:
Create a new variable request and assign a value of false. False is used as the criterion for determining whether an XMLHTTPRequest object has been created.
· Add try/catch blocks:
· Try to create an XMLHTTPRequest object.
1. If catch (failed) fails, ensure that the request value is still false.
2. Check whether the request is still false (if everything is normal, it will not be false ).
· If a problem occurs (request is false), use JavaScript to warn users of a problem.
The code is very simple. For most JavaScript and web developers, it takes longer to really understand it than to read and write code. Now we have a piece of XMLHttpRequest object creation code with an error check, and can tell you where the problem has occurred.
Microsoft
It seems that everything works well, at least before you try the Code with Internet Explorer. If you do this experiment, you will see the bad situation shown in Figure 1.
Figure 1. Internet Explorer reports an error |
Obviously something is wrong, and Internet Explorer is hardly an outdated browser, because 70% of the world is using Internet Explorer. In other words, if Microsoft and Internet Explorer are not supported, they will not be welcomed by the web world! Therefore, we need to use different methods to process Microsoft browsers.
It is verified that Microsoft supports Ajax, but its XMLHttpRequest version has different names. In fact, it calls it something different. If you use a newer version of Internet Explorer, you need to use the msxml2.xmlhttp object, while the older version of Internet Explorer uses Microsoft. XMLHTTP. We need to support these two object types (and also support non-Microsoft browsers ). See Listing 4, which adds support for Microsoft based on the preceding code.
Is Microsoft involved?
There are many articles about Ajax and Microsoft's increasing interest and participation in this field. In fact, it is said that the latest Microsoft version of Internet Explorer-version 7.0 will be available in the second half of 2006-will directly support XMLHttpRequest, allowing you to use the new keyword to replace all msxml2.xmlhttp code. But don't be too excited. You still need to support old browsers, so the cross-browser code will not disappear quickly.
Listing 4. Added support for Microsoft browsers
<Script language = "JavaScript" type = "text/JavaScript"> VaR request = false; Try { Request = new XMLHttpRequest (); } Catch (trymicrosoft ){ Try { Request = new activexobject ("msxml2.xmlhttp "); } Catch (othermicrosoft ){ Try { Request = new activexobject ("Microsoft. XMLHTTP "); } Catch (failed ){ Request = false; } } }If (! Request) Alert ("error initializing XMLHttpRequest! "); </SCRIPT> |
The eyes are easily fascinated by these curly braces, so each step is described below:
· Create a new variable request and assign a value of false. False is used as the judgment condition, indicating that the XMLHTTPRequest object has not been created.
· Add try/catch blocks:
1. Try to create an XMLHTTPRequest object.
2. If catch (trymicrosoft) fails )):
1) try to create a Microsoft-compatible object (msxml2.xmlhttp) with a newer Microsoft browser ).
2) If catch (othermicrosoft) fails, try to create a Microsoft-compatible object (Microsoft. XMLHTTP) in an earlier version of Microsoft browser ).
3) If catch (failed) fails, make sure that the request value is still false.
· Check whether the request is still false (if everything goes well, it will not be false ).
· If a problem occurs (request is false), use JavaScript to warn users of a problem.
In this way, after modifying the code and then using Internet Explorer for testing, you should see the created form (no error message ). The results of my experiment are shown in figure 2.
Figure 2. Internet Explorer works properly |
Static and Dynamic
Take a look at listing 1, 3, and 4. Note that all the code is directly nested in the script tag. JavaScript code like this that is not put into the method or function body is called static JavaScript. That is to say, the code runs at some time before the page is displayed to the user. (Although according to the specification, it is not completely accurate to know when the code will affect the browser, but it can ensure that the code runs before the user can interact with the page .) This is also the general method for most Ajax programmers to create XMLHttpRequest objects.
That is to say, you can put the code in a method like in listing 5.
Listing 5. Move the XMLHttpRequest creation code to the Method
<Script language = "JavaScript" type = "text/JavaScript"> VaR request; Function createrequest (){ Try { Request = new XMLHttpRequest (); } Catch (trymicrosoft ){ Try { Request = new activexobject ("msxml2.xmlhttp "); } Catch (othermicrosoft ){ Try { Request = new activexobject ("Microsoft. XMLHTTP "); } Catch (failed ){ Request = false; } } } If (! Request) Alert ("error initializing XMLHttpRequest! "); } </SCRIPT> |
If you write code in this way, you need to call this method before processing Ajax. Therefore, you also need code like Listing 6.
Listing 6. How to Use XMLHttpRequest to create
<Script language = "JavaScript" type = "text/JavaScript"> VaR request; Function createrequest (){ Try { Request = new XMLHttpRequest (); } Catch (trymicrosoft ){ Try { Request = new activexobject ("msxml2.xmlhttp "); } Catch (othermicrosoft ){ Try { Request = new activexobject ("Microsoft. XMLHTTP "); } Catch (failed ){ Request = false; } } } If (! Request) Alert ("error initializing XMLHttpRequest! "); } Function getcustomerinfo (){ Createrequest (); // Do something with the request variable } </SCRIPT> |
The only problem with this Code is that the error notification is postponed, which is why most Ajax programmers do not adopt this method. Assume that a complex form contains 10 or 15 fields and a selection box. Some Ajax code is activated when a user inputs text in 14th fields (from top to bottom in order of the form. At this time, run getcustomerinfo () to create an XMLHTTPRequest object, but (for this example) failed. Then a warning is displayed to the user, clearly telling them that the application cannot be used. However, the user has spent a lot of time inputting data in the form! This is very annoying, and it is clear that it will not attract users to access your website again. If static Javascript is used, the user will soon see the error message when clicking the page. This is also annoying, isn't it? The user may mistakenly think that your web application cannot run on his or her browser. However, it would be better to display the same error after they input the information for 10 minutes. Therefore, I suggest writing static code so that users can discover problems as early as possible.
Send a request using XMLHttpRequest
After obtaining the request object, you can enter the request/response loop.Remember, the only purpose of XMLHttpRequest is to allow you to send requests and receive responses.Everything else is the work of JavaScript, CSS, or other code on the page: Changing the user interface, switching the image, and interpreting the data returned by the server. After preparing XMLHttpRequest, you can send a request to the server.
Welcome to sandbox
Ajax uses a sandbox security model. Therefore,Ajax code (specifically the XMLHTTPRequest object) can only send requests to the same domain.In future articles, we will further introduce security and Ajax. Now, as long as you know that the code running on the local machine can only send requests to the server scripts on the local machine. If you want Ajax code to run on www.breakneckpizza.com, the request must be sent by a script running on www.breakneck.com.
Set server URL
First, determine the URL of the Connected Server. This is not a special requirement of Ajax, but it is still necessary to establish a connection. Obviously, you should know how to construct a URL. Most applications combine static data with the data in the form processed by the user to construct the URL. For example, the JavaScript code in listing 7 gets the value of the phone number field and uses it to construct a URL.
Listing 7.1 create a request URL
<Script language = "JavaScript" type = "text/JavaScript"> VaR request = false; Try { Request = new XMLHttpRequest (); } Catch (trymicrosoft ){ Try { Request = new activexobject ("msxml2.xmlhttp "); } Catch (othermicrosoft ){ Try { Request = new activexobject ("Microsoft. XMLHTTP "); } Catch (failed ){ Request = false; } } }If (! Request) Alert ("error initializing XMLHttpRequest! "); Function getcustomerinfo (){ VaR phone = Document. getelementbyid ("phone"). value; VaR url = "/cgi-local/lookupcustomer. php? Phone = "+ escape (phone ); } </SCRIPT> |
Listing 7.2 creating requests compatible with ie7.0
<Script language = "JavaScript" type = "text/JavaScript"> VaR request = false; Try { Request = new activexobject ("Microsoft. XMLHTTP "); } Catch (trymicrosoft ){ Try { Request = new activexobject ("msxml2.xmlhttp "); } Catch (othermicrosoft ){ Try { Request = new XMLHttpRequest (); } Catch (failed ){ Request = false; } } } If (! Request) Alert ("error initializing XMLHttpRequest! "); Function getcustomerinfo (){ VaR phone = Document. getelementbyid ("phone"). value; VaR url = "/cgi-local/lookupcustomer. php? Phone = "+ escape (phone ); } </SCRIPT> |
There is nothing difficult to understand here. First, the Code creates a new variable phone and assigns the value of the form field with ID "phone" to it. Listing 8 shows the XHTML of the form. You can see the phone Field and Its ID attribute.
Listing 8. break neck pizza form
<Body> <P> </P> <Form action = "Post"> <P> enter your phone number: <Input type = "text" size = "14" name = "phone" id = "phone" onchange = "getcustomerinfo ();"/> </P> <P> your order will be delivered to: </P> <Div id = "Address"> </div> <P> type your order in here: </P> <P> <textarea name = "order" rows = "6" Cols = "50" id = "order"> </textarea> </P> <P> <input type = "Submit" value = "order pizza" id = "Submit"/> </P> </Form> </Body> |
Note that the getmermerinfo () method shown in listing 8 is triggered when you enter a phone number or change the phone number. This method gets the phone number and constructs a URL string stored in the URL variable. Remember, because Ajax code is sandbox-type, it can only be connected to the same domain. In fact, the URL does not need a domain name. In this example, the script name is/cgi-local/lookupcustomer. php. Finally, the phone number is appended to the script as a get parameter: "phone =" + escape (phone ).
If you have never seen the escape () method before, it is used to escape any characters that cannot be correctly sent in plain text. For example, the space in the phone number will be converted to % 20, so that these characters can be passed in the URL.
You can add any number of parameters as needed. For example, if you want to add another parameter, you only need to append it to the URL and separate it with the "and" (&) character [the first parameter uses Question mark (?) Separated from the script name].
Open request
With the URL to be connected, you can configure the request. You can use the XMLHTTPRequest objectOpen ()Method. This method has five parameters:
· Request-type: Type of the request to be sent. The typical value is get or post, but you can also send HEAD requests.
· URL: the URL to be connected.
· Asynch: true if you want to use an asynchronous connection; otherwise, false. This parameter is optional. The default value is true.
· Username: If authentication is required, you can specify the user name here. This optional parameter has no default value.
· Password: If you need authentication, you can specify a password here. This optional parameter has no default value.
The first three parameters are usually used. In fact, even if an asynchronous connection is required, the third parameter should be specified as "true ". This is the default value, but it is easier to understand whether the request is asynchronous or synchronous.
By combining these, we usually get a line of code shown in listing 9.
Is open () enabled?
Internet developers have not reached an agreement on what to do with the open () method. But it does not actually open a request. If you monitor the network and data transmission between XHTML/ajax pages and their Connection Scripts, you cannot see any communication when you call the open () method. I don't know why I chose this name, but it is obviously not a good choice.
Listing 9. Open a request
Function getcustomerinfo (){ VaR phone = Document. getelementbyid ("phone"). value; VaR url = "/cgi-local/lookupcustomer. php? Phone = "+ escape (phone ); Request. Open ("get", URL, true ); } |
Once the URL is set, the rest is simple. Most requests use get (post is required in later articles), and URL is added. This is all the content required by the open () method.