<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS</title> <style> #box{ width:1000px; min-height:100px; padding:20px; border:1px solid #999; } </style> </head> <body> <h1>ajax 处理复杂的响应结果</h1> <button onclick="loadHtml()">加载</button> <div id="box"></div> <script> function loadHtml(){ // ①实例化 XMLHttpRequest对象 if (window.XMLHttpRequest) { //非IE IE7+ var xhr = new XMLHttpRequest(); } else { //IE 6 var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //② 给xhr 绑定事件, 检测请求的过程 xhr.onreadystatechange = function(){ console.log(xhr.readyState); //如果成功介绍到响应 if (xhr.status == 200 && xhr.readyState == 4) { eval("var data = "+xhr.responseText); //处理数据 makeHtml(data); } } //③ 进行请求的初始化 xhr.open('get', '6.php', true); //④ 正式发送请求 xhr.send(); } //处理返回数据的函数 function makeHtml(data){ var table = document.createElement("table"); table.width = 800; table.border =1; table.cellSpacing =0; table.cellPadding =5; //添加表头 var tr = table.insertRow(0); var th = document.createElement('th'); th.innerHTML = "id"; tr.appendChild(th); var th = document.createElement('th'); th.innerHTML = "name"; tr.appendChild(th); var th = document.createElement('th'); th.innerHTML = "sex"; tr.appendChild(th); var th = document.createElement('th'); th.innerHTML = "grade"; tr.appendChild(th); //添加数据 for (var i =0 ;i < data.length; i ++){ var tr = table.insertRow(i+1); tr.insertCell(0).innerHTML = data[i].id; tr.insertCell(1).innerHTML = data[i].name; tr.insertCell(2).innerHTML = data[i].sex; tr.insertCell(3).innerHTML = data[i].grade; } //追加 table 清空原先的 document.getElementById('box').innerHTML = ""; document.getElementById('box').appendChild(table); } </script> </body> </html>