How to issue asynchronous requests using JavaScript and Ajax (i)

Source: Internet
Author: User
Tags add object error handling html page version variable domain domain name
Ajax|javascript| Request | asynchronous

Most WEB applications use the request/response model to obtain complete HTML pages from the server. Often click on a button, wait for the server to respond, and then click another button, and then wait, such a repetitive process. With Ajax and XMLHttpRequest objects, you can use a request/response model that eliminates the need for the user to wait for a response from the server. In this article, Brett McLaughlin describes how to create a XMLHttpRequest instance that adapts to different browsers, builds and sends requests, and responds to the server.

In this article, you will begin to touch the most basic and basic Ajax-related objects and programming methods: XMLHttpRequest objects. This object is actually just a public thread spanning all Ajax applications, and you may have expected that only a thorough understanding of the object would give full play to the potential of programming. In fact, sometimes you'll find that you can't use XMLHttpRequest to use XMLHttpRequest correctly. What the hell is going on here?

  WEB 2.0 Glimpse

Before delving into the code, take a look at the recent view--be sure to 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 mention Web 1.0, it actually refers to a traditional web with a completely different request and response model. For example, click a button on the Amazon.com site or enter a search term. A request is sent to the server, and then the response is returned to the browser. This request is not just a list of books and bibliographies, but another complete HTML page. So when a Web browser is redrawn with a new HTML page, you may see flicker or jitter. In fact, you can see the requests and responses clearly from each new page you see.

Web 2.0 (to a large extent) eliminates this visible reciprocating interaction. For example, visit sites like Google Maps or Flickr. For example, on Google Maps, you can drag the map, zoom in and out, and only a few redraw operations. Of course there are still requests and responses, but they are hidden behind the scenes. As a user, the experience is more comfortable and feels like a desktop application. This new feeling and paradigm is what you realize when someone mentions Web 2.0.

The need to be concerned is how to make these new interactions possible. Obviously, you still need to make requests and receive responses, but it is the HTML redraw that interacts with each request/response that makes for slow, clumsy Web interaction. So it's clear that we need a way to make requests and receive responses that only contain the data that you need rather than the entire HTML page. The only time you need to get the whole new HTML page is when you want the user to see the new page.

Most interactions, however, add details to existing pages, modify body text, or overwrite existing data. In these cases, Ajax and Web 2.0 methods allow data to be sent and received without updating the entire HTML page. For those who often surf the internet, this ability can make your applications feel faster, respond more promptly, and let them visit your site from time to times.

  XMLHttpRequest Introduction

To truly realize this magnificent miracle, you must be very familiar with a JavaScript object, that is, XMLHttpRequest. This small object has actually been in several browsers for some time, and it is the core of Web 2.0, Ajax, and most of the rest of this column that will be introduced in the next few months. To give you a quick overview of it, here are a few of the few methods and properties that will be used for that object.

    • Open (): Creates a new request to the server.
    • Send (): Sends a request to the server.
    • Abort (): Exits the current request.
    • ReadyState: Provides the ready state of the current HTML.
    • ResponseText: The request response text returned by the server.

If you don't know these (or any of them), you don't have to worry about each of the methods and properties in the next few articles. What you should know now is to be clear about what to do with XMLHttpRequest. Note that these methods and properties are related to sending requests and handling responses. In fact, if you see all the methods and properties of XMLHttpRequest, you'll find that they all have to do with very simple request/response models. Obviously, we're not going to encounter a particularly new GUI object or some very mysterious way to create user interaction, and we'll use very simple requests and very simple responses. It doesn't sound like much attraction, but using that object can completely change your application.

  The Simple new

First you need to create a new variable and assign it a XMLHttpRequest object instance. This is simple in JavaScript, as long as you use the New keyword for the object name, as shown in Listing 1.

Listing 1. Create a new XMLHttpRequest object

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

It's not hard, is it? Remember that JavaScript does not require a variable type to be specified, so you do not need to do this as in Listing 2 (as you might expect in the Java language).

Listing 2. To create a XMLHttpRequest Java pseudo code

XMLHttpRequest request = new XMLHttpRequest ();

So create a variable with var in JavaScript, give it a name (such as "request"), and then assign it a new XMLHttpRequest instance. You can then use the object in the function.

Error handling

In fact all sorts of things can go wrong, and the code above does not provide any error handling. A better approach is to create the object and gracefully exit the problem when it occurs. For example, any older browsers--whether you believe it or not--still use the old version of Netscape Navigator--Do not support XMLHttpRequest, and you need to let these users know that something is wrong. Listing 3 shows how to create the object to emit a JavaScript warning when a problem occurs.

Listing 3. Create a 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:

1. Create a new variable request and assign False value. False is used later as a decision condition, which indicates that the XMLHttpRequest object has not yet been created.
2. Increase the Try/catch block:
An attempt was made to create a XMLHttpRequest object.
Failure (catch (failed)) guarantees that the value of the request is still false.
3. Check that the request is still false (not false if all is normal).
4. If there is a problem (request is false), use the JavaScript warning to notify the user of a problem.

The code is very simple, and for most JavaScript and WEB developers, it takes longer to really understand it than to read and write code. You have now got a XMLHttpRequest object creation code with error checking and can tell you where the problem is.

  Deal with Microsoft

Everything seems to be fine, at least before experimenting with Internet Explorer. If you do this, you will see the bad situation shown in Figure 1.

Figure 1. Internet Explorer reports an error

Clearly something is wrong, and Internet Explorer is hardly an outdated browser because 70% of the world uses Internet Explorer. In other words, Microsoft and Internet Explorer are not welcome in the WEB world if they are not supported! So we need to work with Microsoft browsers in a different way.

It was verified that Microsoft supports Ajax, but its xmlhttprequest version has a different name. In fact, it calls it a few different things. If you are using a newer version of Internet Explorer, you need to use object Msxml2.xmlhttp, while older versions of Internet Explorer use Microsoft.XMLHTTP. We need to support both types of objects (while also supporting non-Microsoft browsers). Take a look at listing 4, which adds support for Microsoft on the basis of the aforementioned code.

Listing 4. Increase 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>

It's easy to be fascinated by these curly braces, so each step is described below:

1. Create a new variable request and assign False value. Using false as a criterion, it indicates that the XMLHttpRequest object has not yet been created.

2. Increase the Try/catch block:

    • An attempt was made to create a XMLHttpRequest object.
    • If failed (catch (Trymicrosoft)):
      1. Try to create a Microsoft-compatible object (MSXML2.XMLHTTP) using a newer version of Microsoft Browser.
      2. If a failure (catch (Othermicrosoft)) attempts to create a Microsoft-compatible object (Microsoft.XMLHTTP) using an older version of Microsoft Browser.
    • Failure (catch (failed)) guarantees that the value of the request is still false.

3. Check that the request is still false (not false if all goes well).

4. If there is a problem (request is false), use the JavaScript warning to notify the user of a problem.

After you modify the code and then use the Internet Explorer experiment, you should see the form you have created (no error messages). The results of my experiment are shown in Figure 2.

Figure 2. Internet Explorer is working properly

Static and dynamic

Take a look at listings 1, 3, and 4, and note that all of this code is directly nested within the script tag. JavaScript code such as this not put into a method or function body is called static JavaScript. This means that the code runs some time before the page is displayed to the user. (although it is not possible to know exactly how the code will function when it is run according to the specification, it can be guaranteed to run before the user can interact with the page.) This is also a common way for most Ajax programmers to create XMLHttpRequest objects.

That is, you can also put the code in one method, as in Listing 5.

Listing 5. To move the XMLHttpRequest creation code into a 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 this way, you need to call the method before you handle Ajax. So you'll need code like listing 6.

Listing 6. Using 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 the delay in error notification, which is why most Ajax programmers do not use this approach. Suppose a complex form has 10 or 15 fields, a selection box, and so on, to activate some Ajax code when the user enters text in the 14th field, from top to bottom in the form order. At this point the GetCustomerInfo () is run to try to create a XMLHttpRequest object, but (for this example) it fails. A warning is then displayed to the user, telling them explicitly that they cannot use the application. But the user has spent a lot of time typing data into the form! This is very annoying, and annoying obviously does not attract users to visit your site again.

If you use static JavaScript, users will quickly see the error message when they click on the page. It's annoying, isn't it? It may make the user mistakenly think that your WEB application cannot run on his browser. But, of course, it's better to show the same error than when they've spent 10 minutes typing in the information. Therefore, I recommend that you write static code that allows users to discover problems as early as possible.

Send request with XMLHttpRequest

After you get the request object, you can enter the request/response loop. Remember, the only purpose of XMLHttpRequest is for 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 images, and interpreting the data returned by the server. Once you are ready to XMLHttpRequest, you can send the request to the server.

Welcome to use the Sandbox

Ajax uses a sandbox security model. Therefore, Ajax code (specifically the XMLHttpRequest object) can only send requests to the same domain in which it resides. Security and Ajax will be introduced further in future articles, so just know that code running on the local machine can only send requests to server-side scripts on the local machine. If you have Ajax code running on www.breakneckpizza.com, you must send the request www.breakneck.com the script that is running in.

Set Server URL

The first step is to determine the URL of the connected server. This is not a special requirement for Ajax, but it is still necessary to establish a connection, and you should now know how to construct the URL. Most applications construct the URL in combination with some static data and data from the user-processed form. For example, the JavaScript code in Listing 7 gets the value of the phone number field and constructs the URL.

Listing 7. 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>

There is no place that is 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 for this form, where 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= "name=" "Phone" id= "Phone"
           />
   </p>
   <p>your order would be Delivered To:</p>
   <div id= "Address" ></DIV>
   <p>type your Order in Here:</p>,
   <p><textarea name= "Order" rows= "6" cols= "M" id= "order" ></ Textarea></p>
   <p><input type= "Submit" value= "Order Pizza" id= "Submit"/></p
  </form>
 </body>

Also note that when a user enters a phone number or changes the phone number, the GetCustomerInfo () method shown in Listing 8 is triggered. This method obtains the phone number and constructs a URL string stored in the URL variable. Remember, because Ajax code is sandbox-type, you can only connect to the same domain, and you don't actually need a domain name in the URL. The script in this example is named/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 character that cannot be sent correctly in clear text. For example, the spaces in the phone number will be converted to the character% 20, allowing these characters to be passed in the URL.

You can add as many parameters as you want. For example, if you need to add another parameter, just attach it to the URL and separate it with the (&) character [the first argument with a question mark (?). Separate from the script name].



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.