javascript - 如何从html接收js函数中的值
问题描述
我正在使用 php 从 html 中的数据库中获取一些数据。我需要将密钥传递给 js 函数,但我做不到。
我需要在下面的代码中使用 html 按钮的函数传递field_id
给updateRecords()
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());
}
?>
解决方案
您的方法签名正在寻找 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 不是数字而是字符串,则必须将其括在引号中以避免引发语法错误。
推荐阅读
- c# - 使用 IMemoryCache 扩展方法的单元测试方法
- android - 允许权限后相机预览不会膨胀,直到应用程序重新启动
- ssh - 如何证明SSH加密数据而Telnet不加密?
- python - 从 Pandas 中的一列列表创建不同的列
- python - Python 类多项式不起作用,就像我期望的那样
- python - Scraping Link Location
- python - Scrapy CrawlSpider:URL 深度
- ansible - 模板化字符串时出现模板错误:意外的字符 u - Ansible
- javascript - 如何在传单地图上显示 SQL 查询
- python - Selenium:如何处理 DOM 中的无效 CSS 选择器