Ajax core object-XMLHTTPRequest object usage (2)

Source: Internet
Author: User
Challenge Asynchronization

Later in this article, I will spend a lot of time writing and using asynchronousCodeBut you should understand why the last parameter of open () is so important. In a common request/response model, for example, Web 1.0, a client (code running on a browser or local machine) sends a request to the server. The request is synchronous. In other words, the client waits for the response from the server. When the client waits, at least some form of notification will be sent to you:

· Hourglass (especially on Windows ).

· Rotating balls (usually on Mac machines ).

· ApplicationProgramBasically frozen, and then the cursor changed for a while.

This is why Web applications are clumsy or slow-lack real interactivity. When you press the button, the application becomes unusable until the newly triggered request gets a response. If a request needs to be processed by a large number of servers, the waiting time may be long (at least in the world where the multi-processor and DSL are not waiting ).

Asynchronous requests do not wait for the server to respond. The application continues to run after the request is sent. You can still enter data in a web form or even exit the form. Applications do not obviously freeze without the rotating ball or hourglass. The server quietly responds to the request and tells the original requester that the work has been completed (the specific method will soon be seen ). The result is that the application does not feel so slow or slow, but responds quickly and interacts with each other. This is only part of Web 2.0, but it is a very important part. All the old GUI components and web design specifications cannot overcome the slow and synchronous request/response model.

Send request

Once configured with open (), you can send the request. Fortunately, the name of the method to send the request is more appropriate than that of open (), which is send ().

Send () has only one parameter, that is, the content to be sent. But before considering this method, let's look back at the previous data that has been sent through the URL itself:

VaR url = "/cgi-local/lookupcustomer. php? Phone = "+ escape (phone );

Although you can use send () to send data, you can also use the URL itself to send data. In fact, in GET requests (about 80% in typical Ajax applications), it is much easier to send data using URLs. If you need to send security information or XML, you may need to use send () to send content. If you do not need to pass data through send (), you only need to pass null as the parameter of this method. Therefore, you will find that in the example in this article, you only need to send the request like this (see listing 10 ).

Listing 10. Sending Requests

Function getcustomerinfo (){
VaR phone = Document. getelementbyid ("phone"). value;
VaR url = "/cgi-local/lookupcustomer. php? Phone = "+ escape (phone );
Request. Open ("get", URL, true );
Request. Send (null );
}

Specify the callback Method

Only a few of what we do now is new, revolutionary, or asynchronous. It must be acknowledged that the small keyword "true" in the open () method creates an asynchronous request. However, the Code is no different from Java Servlet and JSP, PHP, or Perl programming. So what is the biggest secret between Ajax and Web 2.0? The secret lies in a simple attribute of XMLHttpRequest.Onreadystatechange.

First, you must understand the process in the Code (if necessary, review listing 10 ). Create a request and then send the request. In addition, because it is an asynchronous request, the JavaScript method (getcustomerinfo () in this example) will not wait for the server. Therefore, the code will continue to be executed, that is, the control will be returned to the form by exiting the method. The user can continue to enter information, and the application will not wait for the server.

This raises an interesting question: what will happen after the server completes the request? The answer is nothing, at least for the current code! Obviously, this is not the case. Therefore, after the server completes processing the request sent to it through XMLHttpRequest, some instructions are required to explain how to do this.

The onreadystatechange attribute is now available. This attribute allows you to specify a callback function. The callback allows the server (guess ?) Reverse call the code on the web page. It also gives the server a certain degree of control. After the server completes the request, it will view the XMLHTTPRequest object, especially the onreadystatechange attribute. Then, call any method specified by this property. Callback is called because the server initiates a call to the webpage, regardless of what the webpage is doing. For example, this method may be called when a user is sitting in a chair without touching the keyboard, but it may also be called when the user inputs, moves the mouse, scrolls the screen, or clicks a button. It does not care about what the user is doing. This is called asynchronous: the user operates the form on one layer, and the server responds to the request on the other layer and triggers the callback method specified by the onreadystatechange attribute. Therefore, you need to specify this method in the code like in listing 11.

Reference a function in Javascript

Javascript is a weak language that can reference anything with variables. Therefore, if you declare a function updatepage (), JavaScript also regards the function name as a variable. In other words, the updatepage variable name can reference a function in the code.

Listing 11. Setting callback Methods

Function getcustomerinfo (){
VaR phone = Document. getelementbyid ("phone"). value;
VaR url = "/cgi-local/lookupcustomer. php? Phone = "+ escape (phone );
Request. Open ("get", URL, true );
Request. onreadystatechange = updatepage;
Request. Send (null );
}

Note that this attribute is set in the code -- it is set before sending () is called. This attribute must be set before a request is sent, so that the server can view this attribute only after the request is answered. Now, only the updatepage () method is available. This is the focus of the last section in this article.

Process server response

When sending a request, the user is happy to use the web form (the server is processing the request at the same time), and now the server has completed the request processing. The server checks the onreadystatechange attribute to determine the method to be called. In addition, you can think of your application as another application, regardless of whether it is asynchronous or not. In other words, you don't have to take special actions to write the response server method. You just need to change the form so that the user can access another URL or respond to anything the server needs. This section focuses on the response to the server and a typical action-Instantly changing a part of the form that the user sees.

Reconcile Ajax

Now we can see how to tell the server what to do after completion: Set the onreadystatechange attribute of the XMLHTTPRequest object to the name of the function to be run. This function is automatically called after the server processes the request. You do not need to worry about any parameters of the function. We start with a simple method, as shown in listing 12.

Listing 12. Code of the callback Method

It only issues some simple warnings to tell you when the server has completed the task. Test the code on your web page and open it in your browser (see Figure 8 if you want to view XHTML in this example ). Enter the phone number and leave this field. A pop-up warning window appears, as shown in figure 3 ......

 
Figure 3. Ajax code with a warning popped up

Depending on the browser, you will see two, three, or even four warnings before the form stops. What's going on? We have not considered the HTTP readiness status, which is an important part of the request/response loop.

HTTP readiness

As mentioned above, after the server completes the request, it will find the method to be called in the onreadystatechange attribute of XMLHttpRequest. This is true, but not complete. In fact, this method is called whenever the HTTP readiness status changes. What does this mean? First, you must understand the HTTP readiness status.

The HTTP readiness status indicates the Request status or situation. It is used to determine whether the request has started, whether the response has been received, or whether the request/response model has been completed. It can also help determine whether to read the response text or data provided by the server is secure. Five readiness statuses are required for Ajax applications:

0: the request is not sent (before open () is called ).

1: The request has been created but has not been issued (before sending () is called ).

2: The request is being processed (the content header can be obtained from the response ).

3: The request has been processed, and some data is usually available in the response, but the server has not yet completed the response.

4: The response has been completed. You can access the server response and use it.

Like most cross-browser problems, these readiness statuses are also inconsistent. You may expect the task to be ready from 0 to 1, 2, 3 to 4, but this is rarely the case. Some browsers do not report 0 or 1 but start from 2 directly, followed by 3 and 4. Other browsers report all the statuses. In addition, the readiness status 1 is reported multiple times. As you can see in the previous section, when the server calls updatepage () multiple times, a warning box is displayed for each call-which may be different from expected!

For Ajax programming, the only State to be processed directly is ready state 4, which indicates that the server response has been completed and the response data can be safely used. Based on this, the first line of the callback method should be shown in listing 13.

Listing 13. Check readiness

Function updatepage (){
If (request. readystate = 4)
Alert ("server is done! ");
}

After modification, the server processing is completed. Try to run the new version of Ajax code. Now we can see that only one warning message is displayed as expected.

HTTP status code

Although the Code in listing 13 seems good, there is another problem-what if the server responds to the request and completes processing but reports an error? You must know that the server-side code should understand that it is called by Ajax, JSP, common HTML forms, or other types of code, but you can only report information using traditional web-specific methods. In the web world, HTTP code can handle various problems that may occur in requests.

For example, you must have entered an incorrect URL request to get the 404 error code, which indicates that the page does not exist. This is only one of the many error codes that an HTTP request can receive (for a complete list of status codes, see the link in reference ). It indicates that the accessed data is protected or 403 and 401 of Access prohibited are also common. In either case, these error codes are obtained from the completed response. In other words, the server fulfills the request (HTTP readiness status is 4) but does not return the expected data from the client.

Therefore, in addition to the ready status, you also need to check the HTTP status. The expected status code is 200, indicating that everything went well. If the readiness status is 4 and the status code is 200, the server data can be processed, and the data should be the required data (rather than error or other problematic information ). Therefore, you must add a status check in the callback method, as shown in listing 14.

Listing 14. Check the HTTP status code

Function updatepage (){
If (request. readystate = 4)
If (request. Status = 200)
Alert ("server is done! ");
}

To increase the robustness of error handling and avoid being too complex as much as possible, you can add one or two status code checks. Please take a look at the modified updatepage () version in listing 15.

Listing 15. Add an error check

Function updatepage (){
If (request. readystate = 4)
If (request. Status = 200)
Alert ("server is done! ");
Else if (request. Status = 404)
Alert ("request URL does not exist ");
Else
Alert ("error: status code is" + request. status );
}

Change the URL in getcustomerinfo () to a nonexistent URL to see what will happen. The URL specified in the warning information does not exist.-Great! It's hard to handle all the error conditions, but this small change can cover 80% of typical web applications.

Read response text

Now we can ensure that the request has been processed (in the ready state), the server returns a normal response (through the status code), and finally we can process the data returned by the server. The returned data is stored in the responsetext attribute of the XMLHTTPRequest object.

The text content in responsetext, such as the format and length, is intentionally vague. In this way, the server can set the text to any content. For example, a script may return values separated by commas (,), values separated by pipe characters (|), and long text strings. The server determines where to go.

In the example used in this article, the server returns the customer's previous order and customer address, separated by pipeline characters. Then, set the element values in the form using the order and address. Listing 16 shows the code for updating the display content.

Listing 16. Handling server responses

Function updatepage (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
VaR response = request. responsetext. Split ("| ");
Document. getelementbyid ("order"). value = response [0];
Document. getelementbyid ("Address"). innerhtml = response [1]. Replace (/\ n/g ,"");
} Else
Alert ("status is" + request. status );
}
}

First, get responsetext and use the Javascript split () method to separate the pipeline characters. Put the obtained array in response. The first value in the array -- the previous order -- accessed with response [0] and set it to the value of the field with ID "order. The second value response [1], that is, the customer address, requires more processing. Because the rows in the address are separated by the general line separator ("\ n" character), the line Separator in the Code must be replaced by the XHTML style <br/>. The replacement process is completed using the Replace () function and regular expression. Finally, the modified text is used as the internal HTML in the HTML form Div. The result is that the form is suddenly updated with the customer information, as shown in figure 4.

 
Figure 4. break neck form after receiving customer data

Before finishing this article, I will introduce another important attribute responsexml of XMLHttpRequest. If the server chooses to use XML response, this attribute contains (as you may have guessed) XML response. Processing XML responses is very different from processing common text, involving parsing, Document Object Model (DOM) and other issues. TheArticleWe will further introduce XML. However, because responsexml is usually discussed with responsetext, it is necessary to mention it here. Responsetext is enough for many simple Ajax applications, but you will soon see that XML can be well processed through Ajax applications.

Conclusion

You may be tired of XMLHttpRequest. I rarely see a whole article discussing an object, especially this simple object. However, you will use this object repeatedly on every page and application written using Ajax. Frankly speaking, there is something to say about XMLHttpRequest.

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.