Build an AJAX Based ASP.NET Web Tag Application - Part 1
page 3 of 9
by Xianzhong Zhu
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 45139/ 199

Introduction to Prototype

Prototype is a popular fundamental library of reusable JavaScript code, which provides helpful methods and objects that extend JavaScript in a safe and consistent way. Its clever Ajax request model simplifies various cross-browser developments.

For brevity, we are only interested in the Ajax related support by Prototype. As for other concepts, in later sample code we will discuss them.

As an Ajax framework, Prototype provides powerful support concerning various Ajax techniques. In sum, there are the following Ajax related classes and objects introduced in Prototype: Ajax, Ajax.Responders, Ajax.Base, Ajax.Request, Ajax.PeriodicalUpdater, and Ajax.Updater.

Figure 1 - The relationships between the main Ajax classes inside Prototype

In general, the four sub classes in green rectangles in Figure 1 are mostly used. Herein, we plan to reject theories with them, but look at some basic samples relating to the several important classes to lay a firm foundation for the later web tag project.

Sample for Ajax.Request

Probably the most frequently used Ajax class in Prototype is class Ajax.Request. Since the ten or so methods defined in class Ajax.Request are generally used internally, we are not going to discuss them in detail, but turn to see how to use the class Ajax.Request in real cases.

Listing 1 - Sample for the Ajax.Request class

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
 transitional.dtd">
<html>
      <head>
            <title> Sample for the Ajax.Request class </title>
            <script type="text/javascript" language="javascript"
             src="prototype.js" ></script>
            <script type="text/javascript" language="javascript">
            function test() {
                  var myAjax = new Ajax.Request(
                        'http://www.sergiopereira.com/articles/prototype.js.html', 
                        {
                              method: 'get', 
                              onComplete: showResponse
                        }
                  );
            }
            
            function showResponse(response) {
                  $('divResult').innerHTML = response.responseText;
            }
            
            var handle = {
                  onCreate: function() {
                        Element.show('loading');
                  },
                  onComplete: function() {
                        if (Ajax.activeRequestCount == 0) {
                              Element.hide('loading');
                        }
                  }
            };
            Ajax.Responders.register(handle);
            </script>
      </head>
      <body>
      <input type="button" value="click" onclick="test()" />
      <div id="divResult" ></div>
      <div id='loading' style="display:none">
            <img src="loading.gif">Loading...
      </div>
      </body>
</html>

The most important code herein focuses on the test() function. As you have seen, two arguments () are required to initialize the Ajax.Request object. The first argumentrepresents the url of the requested web page (in this case a simple static page "data.html"). The second argument relates to the options that the Ajax operation requires. Note, Prototype has not defined a special class for the Ajax options, but uses an anonymous object to set up the Ajax required parameters. In this sample, there are only two parameters: method indicates the HTTP request mode (by default "POST"), onComplete identifies the callback function to be executed after the Ajax operation returns successfully (i.e. the status of the XMLHttpRequest object equals to 4). In fact, there are still other parameters for the Ajax related operation, and you can refer to the complete official materials here.

For integrity, we have also listed the content of file data.html above, as follow:

some data....

Pretty easy, there is only a short string in it!

Let us next continue with another class, Ajax.Updater.

Sample for Ajax.Updater

In the above Listing, we have succeeded in locally updating a web page by using the "Ajax.Request" class. Due to this kind of functionality, it is often used and for simplification, Prototype derives another sub class "Ajax.Updater" from the parent class "Ajax.Request." In contrast to the "Ajax.Request" class, another parameter container is added to "Ajax.Updater," which represents the id property of the page element to update. Listing 2 illustrates the usage of class Ajax.Updater through which the partial updating in Listing 1 becomes simpler.

Listing 2

…… (omitted)
<head>
    <title>Untitled Page</title>
        <script type="text/javascript" language="javascript"
             src="prototype.js" >
             </script>
             
            <script type="text/javascript" language="javascript">
            function test() {
                  var myAjax = new 
                Ajax.Updater(
                'divResult', // the page element to update
                        'data.html', 
                        {
                              method: 'get', 
                        }
                  );
            }
            </script>
</head>
<body>
          <h1>Sample for the Ajax.Updater class</h1>
          <input type="button" value="click" onclick="test()" />
          <div id="divResult" ></div>
</body>
</html>

Obviously, the code here gets greatly simplified.

In fact, the Ajax.Updater class still owns another function: if the requested page contains some JavaScript code, then the Ajax.Updater can execute the code in it provided we set the property evalScripts to true in the options. For brevity, we will move on to the next topic.

Next, let us continue to see the third important Ajax related class - Ajax.PeriodicalUpdater.

Sample for Ajax.PeriodicalUpdater

Similar to the Ajax.Request class, the Ajax.PeriodicalUpdater class also derives from class Ajax.Base. In some typical Ajax applications, periodically updating some elements on the page is generally required, such as in weather broadcast or live news applications. Before, to achieve such functionality, you usually needed to use the JavaScript's timer related functions, such as setTimeout or clearTimeout. With the help of class Ajax.PeriodicalUpdater, this kind of coding will get drastically simplified.

Similar to class Ajax.Updater, Ajax.PeriodicalUpdater also supports dynamically executing JavaScript codes supposing the Ajax option parameter evalScripts is set to true.

Moreover, Ajax.PeriodicalUpdater introduces another two special Ajax options: frequency and decay. frequency is easy to follow, which specifies the time interval to update some page elements or execute some scripts. However, in special cases, the time interval may not always be fixed when parameter decay comes to help. If the data requested to return is the same as the last time, then the next Ajax operation time will multiply by a coefficient specified by decay.

To gain a more intuitive understanding with the property decay, let us take a related sample (Listing 3).

Listing 3

……(omitted)
<head>
    <title>Untitled Page</title>
        <script type="text/javascript" language="javascript"
             src="prototype.js" >
             </script>
             
            <script type="text/javascript" language="javascript">
            var count = 0;
            function test() {
                  var myAjax = new Ajax.PeriodicalUpdater(
      'script1.html', //the requested url 
      {
            method: 'get',//HTTP request mode
            evalScripts: true, //whether to execute the script in the page
            frequency: 1, //specify the page updating frequency
            decay: 2 //the decaying coefficient
      }
                  );
            }
            </script>
 …… (omitted)   
</head>
<body>
    <h1>Sample for the Ajax.PeriodicalUpdater class</h1>
    <input type="button" value="click" onclick="test()" style="width: 41px" />
    <div id="divResult" ></div>
    <div id="divResult2" ></div>
</body>

Here, we also list the code for file script1.html for your reference.

Listing 4

<script language="javascript" type="text/javascript">
//count the times of Ajax.PeriodicalUpdater calling
count++;
//add a line inside element divResult2
//to record the datetime and 
//the times of Ajax.PeriodicalUpdater calling
var str = $('divResult2').innerHTML;
$('divResult2').innerHTML = str + "count = " + count + ": " + new Date() + "<br>";
</script>

As you have seen, we purposely added the time related script inside file script1.html for you to see the effect of property decay more clearly. Lastly, let us take a look at one of the running-time snapshots for this sample (Figure x).

Figure 2 - Sample for Ajax.PeriodicalUpdater

As you have seen from Figure 2, because the data requested stayed the same, the requesting time interval becomes double of that of the last time. However, once the requested data changes, the requesting time interval is restored to the original value.

Sample for Ajax.Responders

Sometimes, we might want to automatically show an indicator when an AJAX request is ongoing, and hide it when none are. You may well want to factor out exception handling as well, logging those somewhere on the page in a custom fashion. In all these cases, the Ajax.Responders class comes to help. Ajax.Responders lets you register (and if you wish to, unregister later) responders, which are objects with properly-named methods. These names are in fact the regular callback names, and your responders can implement any set of interest.

The example in Listing 4 is created based upon that in Listing 1, which illustrates one of the most typical usages of class Ajax.Responders.

Listing 5

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Sample for the Ajax.Responders class</title> 
 
        <script type="text/javascript" language="javascript"
             src="prototype.js" >
             </script>
             
            <script type="text/javascript" language="javascript">
            function test() {
                  var myAjax = new 
                Ajax.Request(
                        'data.aspx', 
                        {
                              method: 'get', 
                              onComplete:showResponse
                        }
                  );
            }
            
            function showResponse(response) {
                  $('divResult').innerHTML = response.responseText;
            }
            
            var handle = {
                  onCreate: function() {
                        Element.show('loading');
                  },
                  onComplete: function() {
                        if (Ajax.activeRequestCount == 0) {
                              Element.hide('loading');
                        }
                  }
            };
            Ajax.Responders.register(handle);
            </script>
      <style type="text/css">
        #divResult
        {
            height: 45px;
            width: 303px;
            border-style: inset;
            border-color: #008000;
            background-color: #808080;
            color: #FF0000;
        }
    </style>
      </head>
      
      <body>
          <H1>Sample for the Ajax.Responders class</H1>
          <input type="button" value="click" onclick="test()" />
          <div id="divResult" ></div>
          <div id='loading' style="display:none">
                <img alt="img1" src="loading.gif"/>Loading...
          </div>
      </body>
</html>

In this case, we used the method register of class Ajax.Responders to register a set of callback functions: onCreate is called during the Ajax request process and onComplete is called when the Ajax request succeeds. And further by programming the two callback functions, we successfully achieved the effect of prompting the user the Ajax request process using an intuitive .gif animation. Note the requested url is changed into "data.aspx," through which we can more conveniently simulate the server side delay using the Sleep function. The following lists the code for file data.aspx.cs:

Listing 6

protected void Page_Load(object sender, EventArgs e)
{
  System.Threading.Thread.Sleep(3000);
  Response.Write("Data returned from the server...");
}

Lastly, the following Figure indicates one of the running time snapshots during the Ajax request process.

Figure 3 - Sample for Ajax.Responders

Next, let us take a quick look at another Ajax framework, script.aculo.us, which our web tag application rests on to gain more friendly visual effects.


View Entire Article

User Comments

Title: Good   
Name: Sam
Date: 2008-11-03 10:29:16 PM
Comment:
It's very Useful to me
Title: Good   
Name: good choice
Date: 2008-11-01 3:18:04 AM
Comment:
it's very use ful...... thanks
Title: Good!   
Name: Good choice
Date: 2008-10-29 12:30:03 AM
Comment:
I will test your solution on my project ASP in my work.
If all Ok! It would be very very useful... Thnx.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2020 ASPAlliance.com  |  Page Processed at 2020-08-03 9:57:48 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search