Loading XML Using Raw Javascript


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



Copy this code and paste it in your HTML
  1. /*
  2. Author: Alvin Crespo
  3. Description: XMLLoader
  4. */
  5.  
  6. //xml object variable
  7. var xmlhttp;
  8.  
  9. function loadXMLDoc(dname,type){
  10. //get the proper xml object (based on browser of user)
  11. xmlhttp = GetXMLHTTPObject();
  12.  
  13. //if no object was found, tell the user that their browser is not supported
  14. if (xmlhttp==null){
  15. alert ("Your browser is not supported!");
  16. return; //break the current function loadXMLDoc
  17. }
  18.  
  19. //keep track of the state
  20. xmlhttp.onreadystatechange = function(){
  21. //finishing state
  22. if (xmlhttp.readyState==4){
  23. //successful codes: 200 for webserver and 0 for local
  24. if (xmlhttp.status == 200 || xmlhttp.status == 0){
  25. //process code here
  26. if(type == "contact-cards")
  27. createContactCards(xmlhttp.responseXML); //located at contactcards.js
  28. if(type == "contact-profile")
  29. createProfile(xmlhttp.responseXML); //located at profiles.js
  30. }
  31. //let the user know that there was an error loading the xml document
  32. else{
  33. //should handle the error better
  34. alert("Error Loading XML");
  35. }
  36. }
  37. }
  38. //get the document and keep track of what is happening in a queue by setting asynch to true
  39. xmlhttp.open("GET",dname,true);
  40. xmlhttp.send("");
  41. }
  42.  
  43. //get the proper xml object
  44. function GetXMLHTTPObject(){
  45. if (window.XMLHttpRequest){ // for all browsers besides ie 5 and 6 and perhaps 7
  46. return new XMLHttpRequest();
  47. }else if (window.ActiveXObject){ // catch ie 5/6/7
  48. return new ActiveXObject("Microsoft.XMLHTTP");
  49. }
  50. return null;
  51. }
  52. //END OF XML LOADING

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.