Ajax解析XML数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax解析XML数据相关的知识,希望对你有一定的参考价值。

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.
  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. }

以上是关于Ajax解析XML数据的主要内容,如果未能解决你的问题,请参考以下文章

如何解析JQUERY 通过AJAX请求来的HTML数据

jquery请求解析xml

Ajax解析XML数据

JavaScript Ajax解析XML数据

ajax ---- json 和 xml 区别

AJAX学习