【发布时间】:2019-01-15 21:09:04
【问题描述】:
我正在使用 php 从 html 中的数据库中获取一些数据。我需要将密钥传递给 js 函数,但我做不到。
我需要在下面的代码中使用 html 按钮的 onClick() 函数将 field_id 传递给 updateRecords() js 函数。我该怎么做?
之前,我使用相同的代码将值直接发送到 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 的代码。可以看看吗?
edit-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());
}
?>
【问题讨论】:
-
onclick="updateRecords('<?= $row['field_id'] ?>')"...? -
onclick="updateRecords('= $row['field_id'] ?>')"
标签: javascript php html ajax