Ajax Parsing JSON Data


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

This function is near enough the same as parsing XML. The only things that have changed are the sections marked !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 = eval('('+request.responseText+')');//!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 name = data.person.name;//!Important<----------
  29. var position = data.person.position;//!Important<----------
  30. var email = data.person.email;//!Important<----------
  31.  
  32. var theUL = document.createElement("ul");
  33. //name
  34. var nameLI = document.createElement("li");
  35. var nameLIText = document.createTextNode(name);
  36. nameLI.appendChild(nameLIText);
  37. theUL.appendChild(nameLI);
  38. //position
  39. var positionLI = document.createElement("li");
  40. var positionLIText = document.createTextNode(position);
  41. positionLI.appendChild(positionLIText);
  42. theUL.appendChild(positionLI);
  43. //email
  44. var emailLI = document.createElement("li");
  45. var emailLIText = document.createTextNode(email);
  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.