javascript - 当选定的单选按钮更改时从 MySQL 数据库检索图像引用

标签 javascript php html mysql ajax

我有一个 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/

相关文章:

php - 从日期范围选择器获取开始和结束日期

php - 在附加的 <li> 元素上添加工具提示不起作用

javascript - Chrome 显示加载 gif 的方式与 Safari 和 Firefox 不同

javascript - 如何在 PHP 中使用 JavaScript(AJAX) 变量

javascript - jquery中如何获取li元素的点击事件?

php - MySQL 无法识别 MD5

javascript - 如何发布多个复选框列表并处理它们?

javascript - 导航栏 css html 下定位 slider 的问题

javascript - 由 Javascript 添加的 Img 显示 0x0 像素

javascript - 在react组件中使用箭头函数绑定(bind)函数,而不是在构造函数中绑定(bind)