| TechTip: Access XML Web Services with JavaScript |
|
|
|
| Tips & Techniques - Scripting | |||
| Written by Mike Faust | |||
| Thursday, 25 October 2007 | |||
|
Try this practical, working example to see how you can combine AJAX with XML Web services to create truly powerful applications using JavaScript. In a previous TechTip, I introduced you to the JavaScript objects used to access XML Web services via Asynchronous JavaScript and XML (AJAX). This time, I'll expand on what I covered last time and show you a working sample of a Web page. In the previous TechTip, you learned that the key to AJAX is an XMLHttpRequest object. To connect to a remote document using the XMLHttpRequest object, you need to follow a simple series of steps. The first step is to define the XMLHttpRequest object itself. Since Internet Explorer uses a different method of defining this object than other browsers do, your script needs to prepare for this. The statements below show how:if (!ActiveXObject) { xmlHttp = new XMLHttpRequest; } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
In this example, you check for the existence of the ActiveXObject object. If that object does not exist, the document is being displayed on a browser other than Internet Explorer. In that case, the object is defined using the XMLHttpRequest object. Otherwise, it's defined using the ActiveXObject("Microsoft.XMLHTTP") object.
true);
As this example shows, you use the open() method to define how to connect to the Web server; this example uses "GET" along with the URL of the document to be read and the final value indicating that this connection should be made asynchronously, which means that once the send() method is executed, execution of the script will continue without waiting for data to be returned. Then, the send() method sends the request defined on the open() method.
// Defining event handler using a user-defined function
xmlHttp.onreadystatechange = stateHandler(xmlHttp); // Defining event handler using an internal function definition xmlHttp.onreadystatechange = function(xmlHttp) { alert(xmlHttp.readyState); } The first example is fairly cut-and-dried. It simply assigns the onreadystatechange event to the function named stateHandler(). The second example uses a technique whereby the function itself is embedded into the assignment statement. Note that the xmlHttp object is passed as a parameter to each function. Since the onreadystatechange() function is called each time the ready state changes, the application needs to ensure that the code to be performed is executed only if and when the proper state is reached. You can do this by conditioning the code to be executed as shown below:
if (xmlHttp.readyState ==4) {
if (xmlHttp.status == 200) { // Code to be executed once an XML document is opened. } }
This example compares the readyState to 4, which indicates the connection has been made. It also compares the returned status value to 200, indicating that the connection was made successfully.
var xmldoc = xmlHttp.responseXML;
Once that association has been built, the variable xmldoc automatically becomes a type XMLDocument. This type allows us to traverse the entire structure of the returned document.
var myData = xmldoc.getElementsByTagName("datatag");
for (var x = 0; x < myData.length; x++) { document.write(myData.item(x).firstChild.data); }
In this example, you assign the variable myData to the collection associated with the XML tag named "data." The length property is used to determine the upper boundary for a for loop to read through all of the items in this collection. You then use the firstChild.data property to display the values out to the browser. You can also traverse the tree structure using the childNodes() collection. This simple process gives you all the tools you need to access XML data via AJAX. Using AJAX to Read Currency Exchange RatesA discussion of AJAX wouldn't be complete without a working example that helps to fully illustrate the usefulness of this functionality. Figure 1 contains the source for an HTML page that utilizes AJAX to retrieve the noontime currency exchange rate for a given currency code from the Federal Reserve Bank of New York Web service.
Figure 1: This sample consumes the Federal Reserve Bank exchange rate information.
Figure 2: This Web page allows a user to obtain exchange rate data. (Click images to enlarge.)
Figure 3: XML data returned by the Web service is passed back to the user. AJAX: It's Not Just for Cleaning AnymoreAs I hope I've helped to illustrate in this TechTip, when you combine AJAX with XML Web services, you can create truly powerful applications simply using JavaScript. For more information on utilizing JavaScript for business applications, check out the book JavaScript for the Business Developer, new from MC Press. |
|||
| Guest.Visitor |
TechTip: Access XML Web Services with JavaScript
Oct 30 2007 17:50:00 Mike. Good article. <p>Should you use a more recent version of the XML HTTP Request object? They are faster than older versions, probably have bugs worked out too. <p>Example: <a href="http://www.wrox.com/WileyCDA/Section/id-291289.html">http://www.wrox.com/WileyCDA/Section/id-291289.html</a> <p>And a browser might cache an AJAX request with the GET method (heck, POST might be cached too technically) so you might want to stick a unique query string onto the end of the URL every time like this: <p>var noCacheDate = new Date(); <br>
var url = "http://www.somewhere.com?time=" + noCacheDate.getTime(); <p>Chris |
#115918 |
| Guest.Visitor |
TechTip: Access XML Web Services with JavaScript
Oct 30 2007 11:49:00 Good Catch. The odd part is that it doesn't cause an issue on IE6, which is why the example shown worked for generating the screenshots.
|
#115917 |
| g11021 |
TechTip: Access XML Web Services with JavaScript
Oct 26 2007 06:10:00 There is missing a semicolon at the end of the first line in the script <BR>
- var xmlHttp, rateString <p>Regards Jørn |
#115916 |
| MC Press Web Site Staff |
TechTip: Access XML Web Services with JavaScript
Oct 30 2007 17:52:00 This is a discussion about <B>TechTip: Access XML Web Services with JavaScript</b>.<p align='center'><a href=http://www.mcpressonline.com/mc?1@232.1KNKfHX1eQT.17@.6b50a898>Click here for the article</a>.</p>
|
#115915 |






