【发布时间】:2012-10-16 00:19:30
【问题描述】:
我正在尝试从 HTML 表中获取单元格值,以便通过调用 PHP 将它们保存到 MySQL 表中。我想使用 JavaScript 而不是 jQuery。
我根据 MySQL 表的 ID 字段为每个 TR 分配一个不同的 ID。此外,每个 TD 输入单元格都有一个基于 MySQL 表 ID 字段的唯一 ID。不确定我是否需要所有这些,但我使用了它们。
如何获取单元格的值,以便可以将其传递给 PHP 程序(我知道如何编写 PHP 代码)以将数据保存到 MySQL 中?我下面的 JavaScript 代码抓取了“innerHTML”,但我需要抓取单元格值。
例如,如果我有来自 MySQL 表的 3 行数据,字段 id 和 amount,值如下,我如何获取“3”和“1.99”?:
id amount
-------------
1 100.00
2 9.99
3 1.99
以下是表格、提交按钮和 onclick 调用的 PHP/HTML 代码示例: (这是我实际代码的一个非常简化的版本,但应该传达这个想法)
<?php
/* define mysql database connect, query and execute it returning result set into $result, id=integer primary key, is_active=tinyint(0 or 1), amount=decimal(12,2) */
/* ... */
/* output form/table */
echo "<form id='myform' name='myform' >" ;
echo "<table id='mytable' name='mytable'>" ;
while($row = mysql_fetch_array($result))
{
$id = $row['id'] ;
$amount = $row['amount'] ;
$tr_id = "tr_id_" . trim((string)$id) ;
$td_id = "td_id_" . trim((string)$id) ;
$td_amount_id = "td_amount_id_" . trim((string)$id) ;
$input_amount_id = "input_amount_id_" . trim((string)$id) ;
echo "<tr id='$tr_id' name='$tr_id'>";
echo "<td id='$td_id_account' > $id </td>" ;
echo "<td id='$td_amount_id' > <input type='text' id='$input_amount_id' value=$amount > $amount </td>" ;
echo "</tr>";
}
echo "</table>";
echo "</form>" ;
/* submit button and onclick call */
echo "<br />" ;
echo "<table>";
echo "<tr>" ;
echo "<td>";
echo "<button type='button' " . 'onclick="SubmitTableData(\'' . "mytable" .'\');"' . ">Submit</button>" ;
echo "</td>" ;
echo "</tr>";
echo "</table>";
?>
下面是我用来循环遍历 HTML 表格行的 JavaScript 函数示例:
function SubmitTableData(TableID)
{
var table = document.getElementById(TableID);
for (var i = 0, row; row = table.rows[i]; i++)
{
// iterate through rows
for (var j = 0, col; col = row.cells[j]; j++)
{
// iterate through columns
alert(col.innerHTML);
}
/* call PHP procedure with row's cell values as parameters */
/* ... */
break;
}
}
【问题讨论】:
-
你为什么要这样做?必须有一种更简单的方法来完成你想要完成的事情。另外,请发布 生成的 HTML 表格,而不是生成它的 php。
-
我的眼睛.. 看起来非常复杂,无缘无故
标签: javascript php html html-table cell