一、原生js请求
function getList(){ var http = new XMLHttpRequest(); http.open("GET","url",true); http.onload = function (){ if (http.status >= 200 && http.status < 300 || http.status == 304) { var data = http.responseText; var person = JSON.parse(data); var person = person.data.user; //注意返回数据的结构 var table_node = document.getElementById("table"); var tabody_node = document.createElement("tbody"); console.log(tabody_node); table_node.appendChild(tabody_node); for(var key in person){ tabody_node.insertRow(key); for(var attr in person[key]){ var td_node = tabody_node.rows[key].insertCell(-1); var text_node = document.createTextNode(person[key][attr]); td_node.appendChild(text_node); } } }else{ console.log("wocao: " + http.status); console.log(http.statusText); } } http.send(null); }
二、jq请求
function getList(){ $.ajax({ url:"url", type:"get", dataType:"json", success: function(data){ var data = data.data.user; //注意返回数据的结构 var table_node = document.getElementById("table"); var tabody_node = document.createElement("tbody"); table_node.appendChild(tabody_node); for(var key in data){ tabody_node.insertRow(key); for(var attr in data[key]){ var td_node = tabody_node.rows[key].insertCell(-1); var text_node = document.createTextNode(data[key][attr]); td_node.appendChild(text_node); } } }, error:function(e){ console.log(e); } }); }
function getList(){ var tabody = document.getElementById("table"); $.ajax({ url:"url", type:"get", dataType:"json", success: function(data){ var data = data.data.user; //注意返回数据的结构 var str = "<tr>" +"<th>ID</th>" +"<th>用户名</th>" +"<th>密码</th>" +"<th>电话</th>" +"<th>注册时间</th>" +"</tr>"; for(var i in data){ str+= "<tr>" +"<td>" +data[i].uId +"</td>" +"<td>" +data[i].username +"</td>" +"<td>" +data[i].password +"</td>" +"<td>" +data[i].phone +"</td>" +"<td>" +data[i].registerTime +"</td>" +"</tr>"; } tabody.innerHTML = str; }, error:function(e){ console.log(e); } }); }
三、返回结果