使用AJAX和PHP更新图片src

时间:2019-06-02 17:36:05

标签: php mysql ajax

我正在尝试使用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>

displayCase.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。我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:1)

您做了所有正确的事情,除了一个小小的遗漏:您忘记了配置POST数据的数据类型。

在创建XMLHttpRequest之后只需添加适当的标题即可:

xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

添加此代码后,您将发现PHP中已解决缺少$_POST项目的错误。