我正在尝试使用AJAX和PHP根据选定的单选按钮选项更新图像src。
<img class="img-responsive center-block" src="../images/computers/custom-pc1.png" id="buildimage" />
<script>
function updateImage(caseid) {
selectmenuID = document.getElementById(caseid);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("buildimage").src = xhttp.responseText;
}
};
xhttp.open("POST", "displayCase.php", true);
xhttp.send("id=" + selectmenuID);
};
</script>
显示案例.php:
<?php
require_once("config.php");
$id = $_POST['id'];
$stmt = mysqli_prepare($link, "SELECT link FROM cases WHERE id=?");
if(!$stmt) {
die($link->error);
}
$stmt->bind_param("i", $id);
if(!$stmt->execute()) {
die($stmt->error);
}
$stmt->bind_result($image);
$stmt->fetch();
$stmt->close();
echo $image;
?>
我对 php 文件有问题:
未定义的索引:id
。在这一行上:
$id = $_POST['id'];
我想根据所选单选按钮的 ID 更新 src。我做错了什么?谢谢。
除了一个小遗漏之外,您已经做对了一切:您忘记配置 POST 数据的数据类型。
只需在创建XMLHttpRequest
后添加相应的标头:
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
添加此内容后,您会发现缺少$_POST
项的错误已在PHP中解决。