- Recipe: Setting Up an Example Server in Node.js
- Recipe: Performing a GET Request
- Recipe: Loading HTML Directly
- Recipe: Handling the Result by Using Promises
- Recipe: Handling Server Errors
- Recipe: Catching Page-not-Found Results
- Recipe: Handling Page Redirects
- Recipe: Setting Request Timeouts
- Recipe: Passing HTTP Headers
- Example: Validating Form Input on the Server Side
- Recipe: Loading XML
- Recipe: Listening to AJAX Events
- Recipe: Reading JSONP from an External Server
- Summary
Recipe: Loading XML
The original meaning of what was once the acronym AJAX was Asynchronous JavaScript And Xml. The XML part of this name slowly disappeared over time as HTML and JSON have become more popular alternatives (and thus, AJAX is technically no longer an acronym).
If you still want to communicate with the server by using XML, you certainly can. Listing 5.11 demonstrates that jQuery even makes it easy for you to read the XML. It works similarly to selecting HTML elements.
Listing 5.11. Reading XML Values Returned by the Server by Using jQuery
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>Get XML from server</title> 05 </head> 06 <body> 07 08 <h2>Press the button to perform the request.</h2> 09 10 <button id="trigger">GET</button> 11 <br> 12 <div id="target"> 13 14 15 <script src="https://code.jquery.com/jquery-1.7.2.min.js"></script> 16 17 <script> 18 // please externalize this code to an external .js file 19 $(document).ready(function() { 20 21 $('#trigger').click(function() { 22 23 $.get('11a-test-values', function(data) { 24 25 $('#target').append('The returned value is: ' + 26 $(data).find('name').text()); 27 }); 28 29 }); 30 31 }); 32 </script> 33 </body> 34 </html>
Line 26 uses jQuery constructions to read from the XML. The following snippet contains the XML returned by the server:
<?xml version="1.0" encoding="UTF-8" ?> <root> <name>Adriaan de Jonge</name> <email>adriaandejonge@gmail.com</email> </root>
Imagine working with a larger XML example. Using jQuery functions such as those that have been shown, it remains manageable.