首页 > 解决方案 > 如何从html接收js函数中的值

问题描述

我正在使用 php 从 html 中的数据库中获取一些数据。我需要将密钥传递给 js 函数,但我做不到。

我需要在下面的代码中使用 html 按钮的函数传递field_idupdateRecords()js 函数。onClick()我怎样才能做到这一点?

之前,我使用相同的代码将值直接发送到 php。这有点直截了当。现在要实现 ajax,我需要通过将我困在这段代码中的 js。我尝试了不同的解决方案,但到目前为止没有成功。

这是我的代码:

html/php:

<?php
    try {
        $stmt = $conn->prepare("SELECT field_id, description, corner_points, notes FROM fields");
        $stmt->execute();

        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        foreach($stmt->fetchAll() as $row) {
        ?>
          <tr>
                <td style='width:150px;border:1px solid grey;'><?= $row['field_id'] ?></td>
                <td style='width:150px;border:1px solid grey;'><?= $row['description'] ?></td>
                <td style='width:150px;border:1px solid grey;'><?= $row['corner_points'] ?></td>
                <td style='width:150px;border:1px solid grey;'><?= $row['notes'] ?></td>
                <td style='width:150px;border:1px solid grey;'><button class="btn btn-primary btn-sm" name="submit2" type="submit" onclick="updateRecords()">Edit</button></td>
            </tr>
        <?php
        }
    }

这里是接收js:

function updateRecords(field_id) {
    // get values
    //var field_id = $("#field_id").val();

    // Update the details by requesting to the server using ajax
    $.post("ajax/edit-field.php", {
            field_id: field_id,

        },
        function readRecords (data, status) {
            // reload Users by using readRecords();
            readRecords();
        }
    );
}

编辑

我也尝试过这种方法(mentioned in answer1),但没有成功。没有成功我的意思是我遇到了错误,' Notice: Undefined variable: field_id in C:\ajax\edit-field.php on line 43 '.

这是我在 edit-field.php 中用于从 js 接收 field_id 的代码。你能看到它吗?

编辑-field.php

<?php

    if(isset($_GET["field_id"])) //used too if(isset($_POST["field_id"]))       
      {
       $field_id = $_GET["field_id"]; // same here with same results
    }
     try {
            $stmt = $conn->prepare("SELECT field_id, description, corner_points, damming_level_distance_map, pipeline_distance_map, notes FROM fields where field_id = $field_id");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            foreach($stmt->fetchAll() as $row)
            { }
        }

        catch(PDOException $e) {
            exit('<b>Catched exception at line '. $e->getLine() .' (code : '. $e->getCode() .') :</b> '. $e->getMessage());
        }
        ?> 

标签: javascriptphphtmlajax

解决方案


您的方法签名正在寻找 field_id 作为参数,但您从未在 html 中打印它,在服务器端生成它时,更改以下行:

        <td style='width:150px;border:1px solid grey;'><button class="btn btn-primary btn-sm" name="submit2" type="submit" onclick="updateRecords()">Edit</button></td>

    <td style='width:150px;border:1px solid grey;'><button class="btn btn-primary btn-sm" name="submit2" type="submit" onclick="updateRecords(<?= $row['field_id'] ?>)">Edit</button></td>

请记住,如果您的 field_id 不是数字而是字符串,则必须将其括在引号中以避免引发语法错误。


推荐阅读