Chapter 14: Ajax


Overview

Ajax is a new term for a relatively old technique. Ajax is an acronym coined by Jesse James Garrett of Adaptive Path, standing for A synchronous J avaScript A nd X ML. Although it is an acronym, people tend to use it without capitalizing each letter.

The core idea behind Ajax is the use of JavaScript within the browser to transfer and process XML from the server. The asynchronous refers to the fact that this transfer occurs on a background thread, allowing the client to continue to interact with the Web page. Asynchronous download, combined with the fact that only relatively small amounts of XML are transferred, reduces the need for round tripping the entire browser page. This creates a Web application that seems more performant.

This chapter will look at Ajax, and how to add it to your applications. It looks at the main components of any Ajax solution-JavaScript and the XMLHttpRequest object. While not a complete reference on either, the chapter provides basic information on these two topics. In addition, several popular Ajax libraries are highlighted.

The history of Ajax begins around the time of Internet Explorer 5.0, when the XMLHttpRequest object (Microsoft.XMLHTTP) was added to the objects accessible from client-side script.

JavaScript is a scripting language created by Netscape to provide dynamic functionality in Navigator. Originally, it was called LiveScript, but it was later renamed to associate it with Java, which was becoming popular at the time. JavaScript is a loosely-typed, scripting language. That is, it is not compiled. The code is executed through an interpreter (built into most modern browsers). In addition, data types are limited, and variables can change type based on the data stored. For syntax, it takes many cues from the C/C++ family of programming languages. Therefore, you should expect to end each line with a semicolon and use braces ({}) to identify code blocks. JavaScript is a standard (ECMA), so you may hear it referred to as ECMAScript.

Adding JavaScript to a Web Page

You add JavaScript to a Web page in one of two ways: using a script tag, or by adding short blocks of JavaScript directly to events associated with tags on a Web page.

The script tag is the more common form of adding JavaScript to a Web page. The JavaScript can be included within the tag, or the code may be contained within a separate file referenced by the tag.

      //script block      <script language="javascript" type="text/javascript">          alert("Hello world");      </script>      //script in external file      <script type="text/javascript" src="/books/2/381/1/html/2//script/somefile.js"></script> 

Note that the code identifies the type as text/javascript, which is the official MIME type for JavaScript content. You could also use this form when including the JavaScript as a script block, but this is less common.

One problem with adding JavaScript is dealing with browsers that do not accept JavaScript. This is much less of a problem now that most modern browsers can process JavaScript, but a few clients out there are still using Mosaic or Lynx, so it's good technique to comment out (using the HTML comment markers <!-- and -->) the JavaScript to prevent it from appearing in the text of the page on these browsers. Note that this is not necessary if you are including the JavaScript via an external file.

      // Commenting out JavaScript for older browsers      <script language="javascript">      <!--          //your JavaScript here      //-->      </script> 

Notice that the last line in the JavaScript block actually has both the JavaScript (//) and HTML (-->) comments. This is to prevent the JavaScript interpreter from processing the HTML comment.

Functions in JavaScript

You can write your JavaScript in one of two ways: Either use simple statements, or write one or more functions. Loose statements are executed when the script is loaded, whereas functions are called, typically in response to button clicks or other events. Writing functions reveals one of the first major differences between JavaScript and other C-derived languages.

      function sayHello() {          alert("Hello World");      } 

Notice that the function does not require the addition of the return type. The alert() method is a standard JavaScript method that produces a message box containing the text passed in (see Figure 14-1).

image from book
Figure 14-1

In addition to allowing you to create your own functions, JavaScript includes some standard methods you can use in your scripts. Three of these are useful when interacting with users: alert, confirm, and prompt. Alert displays a message box (see Figure 14-1) containing text you specify.

Confirm is similar, but provides OK/Cancel buttons (see Figure 14-2). This enables you to ask simple questions from your scripts.

image from book
Figure 14-2

Finally, prompt provides a text field, enabling user input (see Figure 14-3).

image from book
Figure 14-3

Because JavaScript is text that is interpreted at runtime, it enables different methods of processing than do C# or Java. This is evident in the eval method: This method takes a block of JavaScript and executes it. It is possible to build up a string containing code based on user input and to execute it on demand. This is a powerful (albeit ripe for misuse) feature that you might want to use in the right circumstances.

Data Types in JavaScript

You are not required to identify the types you use when creating variables. However, it is still a good idea to declare the variables before use. This is done with the var keyword.

      var someVariable, someOtherVariable, aThirdVariable; 

The previous statement declares three variables that can hold any data type.

Although JavaScript is a loosely-typed language, it is also object-oriented. You can create your own objects (see Listing 14-1) or make use of the built-in objects. Four of the most common built-in objects in JavaScript are the String, Date, Boolean, and Math objects. These objects provide a number of useful static and instance methods. Some of these methods are shown in the following table.

Open table as spreadsheet

Object

Method/Property

Description

String

length

Returns the length of the string

String

indexOf

Returns the position of the desired substring (0 based)

String

lastIndexOf

Returns the last position of the desired substring (0 based)

String

substring

Extracts a substring from a string and returns it

String

toLowerCase

Converts the string to lowercase and returns it

String

toUpperCase

Converts the string to all uppercase and returns it

Date

getDate

Returns the day of the month (1-31)

Date

getDay

Returns the day of the week (0-6)

Date

getMonth

Returns the month of the year (0-11)

Date

getYear

Returns the year

Date

getFullYear

Returns the four-digit year

Date

getTime

Returns the number of milliseconds since 0:00 GMT January 1, 1970

Date

parse

Converts a string that looks like a date to a date object

Date

set*

Set versions of the above get* methods for Date

Math

min

Returns the smaller of two numbers

Math

max

Returns the larger of two numbers

Math

random

Returns a random number between 0 and 1

Math

PI

Returns the value of pi

Listing 14-1: Creating objects in JavaScript

image from book
      function Person(first, last) {        this.first=first;        this.last = last;      }      Person.prototype.toString = function() {        return this.first + " " + this.last;      }      var p = new Person("John", "Doe");      alert(p.toString()); 
image from book

Language Features of JavaScript

The commonly used looping and conditional blocks of C/C++ are also available in JavaScript (see Listing 14-2). These include if..else, switch, for loops, while loops, and do..while loops.

Listing 14-2: Conditional and loop blocks in JavaScript

image from book
      function isPrime(value) {          var result = true;          for(i=2; i<=Math.sqrt(value);i++) {              if(Math.round(value/i) == value/i) {                  result = false;                  break;              }          }          return result;      }      function getGreeting() {          var currentTime = new Date();          var result;          switch(currentTime.getDay()) {              case 5:                  result = "TGIF";                  break;              case 6:                  result = "Saturday";                  break;              case 0:                  result = "Sunday";                  break;              default:                  result = "Just another work day";                  break;          }          return result;      } 
image from book

In addition to the expected for loops, JavaScript also supports for..in loops. These enable you to iterate over an array or other object that contains a collection of items (see Listing 14-3). The iterator value is set to the index of the item during each loop through the for..in loop.

As you can see from the highlighted code in Listing 5-3, objects are stored as arrays using the property names as keys. You can also iterate over all the properties of an object using the for..in syntax.

Listing 14-3: Using the for..in loop

image from book
      var people = new Array();      people[0] = new Person("John", "Bull");      people[1] = new Person("Jane", "Doe");      for(var person in people) {         alert(people[person].toString());        for(var prop in people[1]) {          alert(prop + ": " + people[person][prop]);        }      } 
image from book

One area of code that always needs attention is error handling. JavaScript supports the try..catch form of exception handling. You wrap the section that might cause an exception in a try block. If an exception occurs, the flow of the code moves to the catch block (see Listing 14-4). There you can handle the error or provide more information to the user as appropriate.

Listing 14-4: Try..catch blocks in JavaScript

image from book
      try {          var answer=prompt('Enter an equation', '6*8');          alert(eval(answer));      } catch(e) {          alert('Could not evaluate that equation');      } 
image from book

In Listing 14-4, the eval method is used to execute the equation entered. If you use the default equation, this should result in a message box showing 48. However, if you enter an equation with an error or with code that cannot be evaluated, the message box shows the error message.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net