游.程 2017-12-11 12:25 采纳率: 0%
浏览 28

jQuery .getJSON()数组作为表

I am currently working with a project where a query is sent to a server using jQuery and the response returned is an array. I am however getting stuck with being able to send the received data to a dynamic table as the column count may differ between queries. So far I have the following but cant seem to parse the array to the table:

<script>
var my_array;
$.getJSON("sql_query.php", // The server URL 
    { id: "sewer_pipelines" },
    function(json) {
    my_array = json;
    });

function generate_table() {
    // Create a HTML Table element.
    var table = document.createElement("TABLE");
    table.border = "1";

    // Get a column count
    var column_count = my_array[0].length;

    // Add header row
    var row = table.insertRow(-1);
    // Creates a loop 
    for (var i = 0; i < column_count; i++) {
        row = table.insertRow(-1);
        for (var j = 0; j < column_count; j++);
            var cell = row.insertCell(-1);
            cell.innerHTML = my_array[i][j];
    }

    var array_table = document.getElementById("array_table");
    array_table.innerHTML = "";
    array_table.appendChild(table);
};
</script>

<html>
    <input type="button" value="Generate Table" onclick="generate_table()" />  
    <div id="array_table"></div>
</html>

The array returned is in the format:

[{"gid":"2","id":"BOS_SE0131","layer":"BOS_SE0131"},
{"gid":"3","id":"BOS_SE0130","layer":"BOS_SE0130"},
{"gid":"4","id":"BOS_SE0133","layer":"BOS_SE0133"}]

Would getting the array variable into the second function work or am I on the completely wrong track?

  • 写回答

3条回答 默认 最新

  • weixin_33711647 2017-12-11 12:49
    关注

    As you are using jQuery already, you can try this approach:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
    <script>
      var my_array = [
       {"gid":"2","id":"BOS_SE0131","layer":"BOS_SE0131"},
       {"gid":"3","id":"BOS_SE0130","layer":"BOS_SE0130"},
       {"gid":"4","id":"BOS_SE0133","layer":"BOS_SE0133"}
      ];
    
      function generate_table() {
        // Create a HTML Table element.
        var table = $("<table border='1'></table>");
    
        table.append($("<tr><th>GID</th><th>ID</th><th>Layer</th>"))
        for (var i = 0; i < my_array.length; i++) {
          table.append($("<tr><td>" + my_array[i]['gid'] + "</td><td>" + my_array[i]['id'] + "</td><td>" + my_array[i]['layer'] + "</td>"))
        }
    
        $("#array_table").html('')
        $("#array_table").append(table);
      };
    </script>
    <input type="button" value="Generate Table" onclick="generate_table()" />
    <div id="array_table"></div>
    
    </html>

    </div>
    
    评论

报告相同问题?