我有一个 MySQL 数据库,用于存储图像的路径。
我希望显示的图像根据所选的单选按钮选项进行更改。我正在尝试使用AJAX来更新显示的图像,但我对这项技术的理解非常有限。
这是单选按钮列表和图像。当所选元素发生变化时,将调用 JS 函数。
<img class="img-responsive center-block" src="../images/1.png" id="buildimage" />
<ul id="radio" class="input-list">
<li>
<input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateImage(this.id);">
<label for="item-1">Item 1</label>
</li>
<li>
<input id="item-2" name="config-prod" value="2.00" type="radio" onchange="updateImage(this.id);">
<label for="item-2">Item 2</label>
</li>
<li>
<input id="item-3" name="config-prod" value="3.00" type="radio" onchange="updateImage(this.id);">
<label for="item-3">Item 3</label>
</li>
</ul>
这是函数 updateImage:
<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").innerHTML = this.responseText;
}
};
xhttp.open("GET", "displayImage.php", true);
xhttp.send("id='selectmenuID'");
}
</script>
检索路径的 PHP 文件:
<?php
require_once("config.php");
$id = $_GET["id"];
$stmt = $pdo->prepare("SELECT link FROM cases WHERE id=?");
$stmt->bind_param("s", $id);
$stmt->execute([$id]);
$result = $stmt->fetch();
echo '<img src="data:image/jpeg;base64,'.base64_encode($result['image'] ).'"/>';
?>
我遇到的问题是我不明白如何使用 AJAX 调用传递所选元素 ID 的 PHP 文件,然后根据响应更改 src 文件路径。
这可能吗?谢谢。
最佳答案
首先,您必须使用 xhttp.responseText
而不是 this.responseText
来从服务器获取响应。
然后,您应该直接替换图像的 src
属性,而不是尝试替换其 html :
document.getElementById("buildimage").src = xhttp.responseText;
服务器端:
echo $result['image'];
您还必须替换此行:
xhttp.send("id='selectmenuID'");
通过这个:
xhttp.send("id="+selectmenuID);
关于javascript - 当选定的单选按钮更改时从 MySQL 数据库检索图像引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56411294/