使用Javascript对象动态创建html表

时间:2017-07-26 15:36:24

标签: javascript jquery html mysql json

我正在尝试使用MySQL表中的数据动态创建HTML表。表中的数据不是静态的,因此需要在数据库表更新时更新HTML表。

这是我的PHP代码:

 $sql = "SELECT * FROM pendingusers";
$result = $conn->query($sql);
$response = array(); //$result->fetch_all(MYSQLI_ASSOC);

if ($result->num_rows > 0) {
    $i = 1;
    while($row = $result->fetch_assoc()) //$response[] = $row; 

{    

    $response[$i]['fname'] = $row["firstname"];
    $response[$i]['lname'] = $row["lastname"];
    $response[$i]['uname'] = $row["username"];
    $response[$i]['email'] = $row["email"];
    $response[$i]['password'] = $row["password"];
    $i++;
}

 echo json_encode($response);   

} else {
    echo "0 results";
}
$conn->close();

?>

这是我调用PHP文件的Javascript函数:

function load() {   

            // var users = null;    
            $.post(
            "Returnsmedb.php",
            function (response) {
               console.log(response);
            }, 'json'
        );           
}

这将返回一个对象,其中包含三个内部对象,每个对象代表一行,如下所示:Object {1:Object,2:Object,3:Object}。每个内部对象都有字段email,fname,lname,password,uname。

我不知道从哪里开始。我认为这需要转换为JavaScript数组,但我没有找到很好的例子。如何将这些数据放入表中需要做什么?

表格的每一行应对应一个具有适当字段标题的内部对象。此外,每行需要有两个按钮,将从表中删除它或将值添加到另一个数据库表。

2 个答案:

答案 0 :(得分:1)

以下是使用jQuery根据数据构建HTML标记的方法之一。



var data = [
{
  email: "abc@def.ghi", 
  fname: "abc", 
  lname: "def", 
  password: "abcDef",
  uname: "defAbc"
},{
  email: "1abc@def.ghi", 
  fname: "2abc", 
  lname: "3def", 
  password: "4abcDef",
  uname: "5defAbc"
},{
  email: "6abc@def.ghi", 
  fname: "7abc", 
  lname: "8def", 
  password: "9abcDef",
  uname: "0defAbc"
}
];

var tableBody = "";

var columns = [];

// Create the header record.
tableBody = tableBody + "<tr>";
for(var prop in data[0]) {
  if(data[0].hasOwnProperty(prop)) {
    // Append properties such as email, fname, lname etc.
    tableBody = tableBody + ("<th>" + prop + "</th>");
    
    // Also keep a list of columns, that can be used later to get column values from the 'data' object.
    columns.push(prop);
  }
}

tableBody = tableBody + "</tr>";

// Create the data rows.
data.forEach(function(row) {
  // Create a new row in the table for every element in the data array.
  tableBody = tableBody + "<tr>";

  columns.forEach(function(cell) {
    // Cell is the property name of every column.
    // row[cell] gives us the value of that cell.
    tableBody = tableBody + "<td>" + row[cell] + "</td>";
  });
  
  tableBody = tableBody + "</tr>";
});

$("#usersTable").append(tableBody);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="usersTable">

</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下是我如何使用它。

function load() {   


            $.post(
            "Returnsmedb.php",
            function (response) {

                var block = []

                index = 0;
                for (var item in response){

                    var objectItem = response[item];

                  var firstname = objectItem.fname;
                  var lastname = objectItem.lname;
                  var username = objectItem.uname;
                  var email = objectItem.email;
                  var password = objectItem.password;
                  var deny = document.createElement("input");
                  deny.type = "checkbox";
                  deny.className = "chk";
                  deny.name = "deny";
                  deny.id = "deny";
                  var approve = document.createElement("input");
                  approve.type = "checkbox";
                  approve.className = "chk";
                  approve.name = "approve";
                  var moreinfo = document.createElement("input");
                  moreinfo.type = "checkbox";
                  moreinfo.className = "chk";
                  moreinfo.name = "moreinfo";

                    block.push(firstname);
                    block.push(lastname);
                    block.push(username);
                    block.push(email);
                    block.push(password);
                    block.push(deny);
                    block.push(approve);
                    block.push(moreinfo);

                    dataset.push(block);
                    block = [];


                }




                 var data = [" First Name", " Last Name "," User Name ", " Email ", "Password", " Deny", "Approve", "More Information"]

                tablearea = document.getElementById('usersTable');
                table = document.createElement('table');
                thead = document.createElement('thead');
                tr = document.createElement('tr');

                for (var i = 0; i < data.length; i++) {
                    var headerTxt = document.createTextNode(data[i]);
                    th = document.createElement('th');
                    th.appendChild(headerTxt);
                    tr.appendChild(th);
                    thead.appendChild(tr);
                }

                table.appendChild(thead);


                for (var i = 0; i < dataset.length; i++) {
                    tr = document.createElement('tr');
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td')); //Added for checkbox
                    tr.appendChild(document.createElement('td')); //Added for checkbox
                    tr.appendChild(document.createElement('td')); //Added for checkbox


                    tr.cells[0].appendChild(document.createTextNode(dataset[i][0]));
                    tr.cells[1].appendChild(document.createTextNode(dataset[i][1]));
                    tr.cells[2].appendChild( document.createTextNode(dataset[i][2]));
                    tr.cells[3].appendChild( document.createTextNode(dataset[i][3]));
                    tr.cells[4].appendChild( document.createTextNode(dataset[i][4]));
                    tr.cells[5].appendChild((dataset[i][5])); //
                    tr.cells[6].appendChild((dataset[i][6])); //
                    tr.cells[7].appendChild((dataset[i][7])); //
                    table.appendChild(tr);                   
                }
                tablearea.appendChild(table);


                $('input.chk').on('change', function() {
                if($('this:checked'))
                {
                    var tr =$(this).parents('tr');
                tr.find("input.chk").not(this).each(function(){
                $(this).prop('checked', false);
                });
                }

                });
            }, 'json'
        );           
}