Introduction to XMLHttpRequest

Source: Internet
Author: User
  Introduction to XMLHttpRequestTo 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 understand this (or any of them), you don't have to worry about it. In the following articles, we will introduce 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 newCreate 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> is not difficult? 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 ). List 2. create a Java pseudo-code XMLHttpRequest request = new XMLHttpRequest () for XMLHttpRequest. Therefore, use var to create a variable in JavaScript and give it a name (such as "request "), then assign it a new XMLHttpRequest instance. Then you can use this object in the function. Error HandlingIn 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. create XMLHttpRequest with error handling capabilities <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. MicrosoftIt 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 the Microsoft browser <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> is easily fascinated by these curly braces, so the following describes each step: · 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): 1) try to create a Microsoft-compatible object (Msxml2.XMLHTTP) in a newer version of 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 DynamicTake 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. use the XMLHttpRequest creation 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! ");} Function getCustomerInfo () {createRequest (); // Do something with the request variable} </script> the only problem with this Code is that the error notification is postponed, this 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 XMLHttpRequestAfter 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 JavaScript , CSS Or other code work on the page: Change the user interface, switch the image, and explain the data returned by the server. After preparing XMLHttpRequest, you can send a request to the server.   Welcome to sandboxAjax 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 URLFirst, 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 sets up a request 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> This is not difficult to understand. 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 this form. The phone Field and Its id attribute are displayed.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: </p> <div id = "address"> </div> <p> Type your order in here: </p> <textarea name = "order" rows = "6" cols = "50" id = "order"> </textare A> </p> <input type = "submit" value = "Order Pizza" id = "submit"/> </p> </form> </body> note, when you enter a phone number or change the phone number, the getmermerinfo () method shown in listing 8 is triggered. 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 requestWith the URL to be connected, you can configure the request. You can use the open () method of the XMLHttpRequest object. 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 the 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 will be 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.

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.