本文實例講述了jQuery ajax動態生成table的方法。分享給大家供大家參考,具體如下:
$(function(){ ajaxT(); }); function ajaxT(){ $.ajax({ type:"POST", dataType: "json", url:"<%=basePath%>UserInfoServlet", data:"doaction=userList", success:function(data){ createShowingTable(data); } } ); } //動態的創建一個table function createShowingTable(data) { var tableStr = "<table class='tab-list' width='99%'>"; tableStr = tableStr + "<tr class='list-header'>" +"<td width='5%'>序號</td>" +"<td width='5%'><input id='checkAll' name='checkAll' type='checkbox' /></td>" +"<td width='30%'>用戶姓名</td>" +"<td width='20%'>工號</td>" +"<td width='20%'>職位</td>" +"<td width='20%'>創建時間</td>" +"</tr>"; var len = data.length; for ( var i = 0; i < len; i++) { tableStr = tableStr + "<tr>" +"<td>"+ (i+1) + "</td>" +"<td><input class='check' id='checkOne' name='checkOne' type='checkbox' value='"+data[i].key+"' /></td>" +"<td>"+ data[i].realName + "</td>" + "<td>"+ data[i].userNo + "</td>" + "<td>"+ data[i].position + "</td>" +"<td>"+data[i].regTime+"</td>" +"</tr>"; } if(len==0){ tableStr = tableStr + "<tr style='text-align: center'>" +"<td colspan='6'><font color='#cd0a0a'>"+ 暫無記錄 + "</font></td>" +"</tr>"; } tableStr = tableStr + "</table>"; //添加到div中 $("#tableAjax").html(tableStr); }