Ajax解析JSON数据

Posted

tags:

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

This function is near enough the same as parsing XML. The only things that have changed are the sections marked !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 = 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. }

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

如何解析从 Datatables ajax 调用收到的 JSON?

如何在 Django 视图中使用 ajax POST 解析 json 数据

如何格式化通过 AJAX 从 ASPX JSON 解析的日期?

ajax请求时如何解析json数据

AJAX如何解析后台传来的json数据?

Ajax请求的Json解析以及Post与Get方法