Java Reference
In-Depth Information
This is another area in which Ajax solutions, and XMLHttpRequest specifi cally, miss the mark. This
problem, however, is simple to overcome: Simply add UI elements to tell the user something is going on
and remove them when the action is completed. Consider the following code:
function requestComplete(sResponseText)
{
//do something with the data here
document.getElementById(“divLoading”).style.display = “none”;
}
var myRequest = new HttpRequest(“http://localhost/myfile.txt”, requestComplete);
document.getElementById(“divLoading”).style.display = “block”;//show that we're
loading
myRequest.send();
This code uses the HttpRequest module built earlier to request a text fi le. Before sending the request,
retrieve an HTML element in the document with an id of divLoading. This <div/> element tells the
user that data is loading; hide it when the request completes, which lets the user know that the loading
process is completed.
Offering this information to your users lets them know the application is performing some operation
that they requested. Otherwise, they may wonder if the application is working correctly when they click
something and see nothing instantly happen.
Degrade Gracefully When Ajax Fails
In a perfect world, the code you write would work every time it runs. Unfortunately, you have to face
the fact that many times Ajax-enabled web pages will not use the Ajax-enabled goodness because a user
turned off JavaScript in his browser.
The only real answer to this problem is to build an old-fashioned web page with old-fashioned forms,
links, and other HTML elements. Then, using JavaScript, you can disable the default behavior of those
HTML elements and add Ajax functionality. Consider this hyperlink as an example:
<a href=”http://www.wrox.com” title=”Wrox Publishing”>Wrox Publishing</a>
This is a normal, run-of-the-mill hyperlink. When the user clicks it, it will take them to http://
www.wrox.com. By using JavaScript, you can override this action and replace it with your own.
<a href=”http://www.wrox.com” title=”Wrox Publishing”
onclick=”return false;”>Wrox Publishing</a>
The key to this functionality is the onclick event handler, highlighted in this code, and returning a
value of false. You can execute any code you wish with the event handler; just remember to return
false at the end. This tells the browser to not perform its default action when the link is clicked. If the
user's JavaScript is turned off, the onclick event handler is ignored, and the link behaves as it nor-
mally should.
As a rule of thumb, build your web page fi rst and add Ajax later.
Search WWH ::




Custom Search