Ajax Parsing XML Data


/ Published in: JavaScript
Save to your folder(s)

This function allows you to parse a simple XML document(passed to it using this.href on a onclick event). Virtually the same as JSON, the things that have been changed ate labeled !Important.


Copy this code and paste it in your HTML
  1. function basicAJAX(file) {//pass a variable into the function
  2. var request = getHTTPObject();
  3. if(request){
  4. request.onreadystatechange = function() {
  5. parseResponse(request);
  6. };
  7. request.open("GET", file, true);//this is where the var is picked up, the location
  8. request.send(null);
  9. }
  10. }
  11. function parseResponse(request) {
  12. if(request.readyState == 4){//waits for the complete before execute.
  13. if(request.status == 200 || request.status == 304){
  14. var data = request.responseXML;//!Important <-----------------
  15. createInfo(data);
  16. } else {
  17. alert("Something Broke!");
  18. }
  19. }
  20. }
  21. function createInfo(data) {
  22. var holder = document.getElementById("showDiv");//the holder div
  23.  
  24. while(holder.hasChildNodes()){
  25. holder.removeChild(holder.lastChild);
  26. }
  27. //grab the info
  28. var personName = data.getElementsByTagName("name");//!Important <-----------------
  29. var personPosition = data.getElementsByTagName("position");//!Important <-----------------
  30. var personEmail = data.getElementsByTagName("email");//!Important <-----------------
  31.  
  32. var theUL = document.createElement("ul");
  33. //name
  34. var nameLI = document.createElement("li");
  35. var nameLIText = document.createTextNode(personName[0].firstChild.nodeValue);
  36. nameLI.appendChild(nameLIText);
  37. theUL.appendChild(nameLI);
  38. //position
  39. var positionLI = document.createElement("li");
  40. var positionLIText = document.createTextNode(personPosition[0].firstChild.nodeValue);
  41. positionLI.appendChild(positionLIText);
  42. theUL.appendChild(positionLI);
  43. //email
  44. var emailLI = document.createElement("li");
  45. var emailLIText = document.createTextNode(personEmail[0].firstChild.nodeValue);
  46. emailLI.appendChild(emailLIText);
  47. theUL.appendChild(emailLI);
  48.  
  49. holder.appendChild(theUL);
  50. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.