我有index.php页面,其中数据从数据库中提取并显示为简单的表格(可以使用我的js脚本选择每一行)。
我有一个 js 脚本,它执行所有选择并将表中的 ID 号存储到 js 变量中。
$(function() {
/* Get all rows from table but not the first one
* that includes headers. */
var rows = $('tr').not(':first');
/* Create 'click' event handler for rows */
rows.on('click', function(e) {
/* Get current row */
var row = $(this);
/* highlights the row*/
rows.removeClass('highlight');
row.addClass('highlight');
/*outputs the ID of the selected row to rowID variable*/
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").html();
var rowID=col1;
});
});
我有另一个 dbUpdate.php 脚本,其中包含 html 表单和 php 查询。
if( !$_POST["e1"] ){
$e1Error = "Please enter value <br>";
} else {
$e1 = validateFormData ( $_POST["e1"] );
}
if( !$_POST["rowID"] ){
$rowID = validateFormData ( $_POST["rowID"] );
}
// check variable has data
if( $e1 && $rowID ) {
$query = "UPDATE athletes SET e1 = ($e1) WHERE id = ($rowID) ";
这是 html 表单
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<small class="text-danger">* <?php echo $e1Error; ?></small>
<input type="text" placeholder="e1" name="e1"><br><br>
<input type="hidden" id="rowID1" name="rowID" value=""/>
我的目标是当我选择 html 表中的某一行(如图所示)时,从 js 变量 rowID 获取该 ID 号并将其存储在我的 dbUpdate.php 表单(name="rowID")中。
最佳答案
这是一个 ajax
示例(使用 jQuery 语法,因为这就是您正在使用的语法):
rows.on('click', function(e) {
$.ajax({
url: '/dbUpdate.php',
type: 'POST',
data: { rowID: $(rowID).val() },
cache: true,
success: function (data) {
alert('Woot!');
}
, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); }
});
});
现在,显然,这只会将返回值拉回您的成功函数中。如果您尝试让 dbUpdate.php
页面将 html 返回给客户端,那就是另一回事了。你到底想做什么?
关于javascript - 使用 js 变量作为将在 php 查询中使用的 html 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42012201/