首页 > 解决方案 > 从 HTML 表中提取数据以将值存储在变量中

问题描述

我想知道如何将数据库中的值放入javascript中的变量中。我不是网络开发人员,所以我在 HTML/CSS/Javascript 方面没有那么丰富的经验,因此不胜感激。我的代码如下:

$(document).ready(function() {

    $("#display").click(function() {

        $.ajax({ //create an ajax request to display.php
            type: "GET",
            url: "GetOccupancy.php",
            dataType: "html", //expect html to be returned
            success: function(response) {
                $("#responsecontainer").html(response);
                //alert(response);
            }
        });
    });
});

function GetCellValues() {
    var table = document.getElementById('#responsecontainer');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].innerHTML);
        }
    }
}

标签: javascripthtml

解决方案


好吧,一种方法是设置一个二维数组(矩阵),然后将值推入:

function GetCellValues() {
    var table = document.getElementById('#responsecontainer');

    var tableMatrix = []; //Set up an empty array (put it outside the function if you want to use it again somewhere else)

    for (var r = 0, n = table.rows.length; r < n; r++) {

        var rowValues = []; //Create an array to hold all the values in this row

        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            
            rowValues.push( table.rows[r].cells[c].innerHTML ); //Add the values to the row
            
        }

        tableMatrix.push(rowValues); //Now add the row to the table matrix
    }
}

但是,这实际上取决于您希望如何访问它。事实上,它可能按原样可用 - 即您可以复制table.rows到一个新变量并以这种方式存储它。这一切都取决于你想用它做什么。


推荐阅读