javascript - 使用 js 变量作为将在 php 查询中使用的 html 表单

标签 javascript php jquery html mysql

我有index.php页面,其中数据从数据库中提取并显示为简单的表格(可以使用我的js脚本选择每一行)。

enter image description here

我有一个 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/

相关文章:

PHP: "Value Expected To Be A Reference"与 Call_User_Func 和绑定(bind)参数

php - 如何使用 Yii 验证多个模型?

javascript - goodreads API 给出了 Cross-Origin Request Blocked : error in javascript

javascript - 使用 Kartik 文件输入上传图像

php - 二叉树中的递归函数调用

javascript - FullCalendar 按钮放置月份名称应位于左右箭头之间

jQuery FullCalendar 获取事件优化

javascript - 选择决定打开哪个表单操作

javascript - 嵌套 Bootstrap Collapse 事件类问题

javascript - 如何使用 Azure 移动服务 API 功能