使用AJAX从下拉列表中更改图像

时间:2017-12-04 13:25:43

标签: php html css navigation

这里我有一个下拉菜单,其中选择其他下拉列表更改会导致其他下拉列表的ID为" style_code"。现在我也想在下拉选择中更改图像,就像当我从下拉列表中选择颜色时,它会改变其他下拉列表的大小,但我也想在颜色选择上更改图像。

<script>
    function getState(val) {
        $.ajax({
            type: "POST",
            url: "check.php",
            data:'id='+val,
            success: function(data){
                $("#style_code").html(data);
            }
        });
    }
</script>

这是check.php

<?php 

$con=mysqli_connect("localhost","root","","db") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con,$query);

    while ( ($row=mysqli_fetch_array($results))){?>
        <option value="<?php echo $row["color_name"]; ?>">
            <?php echo $row['size'] ; ?>
        </option>
<?php
    }
}
?>

1 个答案:

答案 0 :(得分:1)

您的困难来自于您从PHP脚本返回HTML代码的事实。我的建议是返回JSON数据,然后使用jQuery生成 style_code 子项。

会是这样的:

<强> check.php

<?php 

$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con, $query);

    $data = new stdClass(); // This object will carry the results

    while (($row = mysqli_fetch_object($results))) {
        $data->option[] = $row;
    }

    // Another query to get the image name
    $query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con, $query);

    if ($row = mysqli_fetch_object($results)) {
        $data->image_name = $row->name;
    }

    header('Content-Type: application/json');
    echo json_encode($data);

}

HTML&amp;使用Javascript:

...

<div class="thumb-image" id="style_image" >
    <img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>

...

<script language="javascript">
function getState(val) {
    $.ajax({
        type: "POST",
        url: "check.php",
        data: {id: val},
        dataType:'json',
        success: function(data) {
            $("#style_code").children().remove(); // empty the dropdown
            // Add new options in the dropdown from the result data
            data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
            });
            // Change the 'src' attribute of the <img>
            $("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
        }
    });
}
</script>