gpt4 book ai didi

javascript - 从另一个下拉列表填充下拉列表

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:06 24 4
gpt4 key购买 nike

我正在尝试根据在另一个选择菜单上选择的值填充一个选择菜单。

到目前为止,我设法获得了值,并且我的 PHP 代码确实以 JSON 形式返回值。但是,我似乎无法弄清楚如何在下一个选择菜单中显示数据。

<div class="form-group">
<label for="laptopBrand">Laptop Brand</label>
<select class="form-control" id="laptopBrand">
<?php foreach($laptop_brands as $laptop_brand): ?>
<option value="<?= $laptop_brand['Lbrand'] ?>"><?= $laptop_brand['Lbrand'] ?></option>
<?php endforeach; ?>
</select>
</div>

<div class="form-group">
<label for="laptopSeries">Laptop Series</label>
<select class="form-control" id="laptopSeries">
</select>
</div>

JQuery

$("#laptopBrand").change(function(){
var lbrand = $(this).val();
$.ajax({
type: "POST",
data: 'laptopSeries='+lbrand,
url: 'includes/fetch.php',
dataType: 'json',
success: function(json) {
var a = JSON.parse(json);
alert(a);
var $el = $("#laptopSeries");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});

PHP

if($_POST){
$laptopSeries = $_POST['laptopSeries'];
try{
$stmt = $db_con->prepare("SELECT `Lseries` FROM `laptop` WHERE `Lbrand` = '$laptopSeries'");
$stmt->execute();
$series = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($series as $series) {
$array = array($series['Lseries'] => $series['Lseries']);
echo json_encode($array);
}

}catch(PDOException $e){
echo $e->getMessage();
}
}

最佳答案

这样做并确保您的服务器代码返回您想要填写的键和值。

$.each(a,function(key, value)  // a or jsondata

{

$select.append('<option value=' + key + '>' + value + '</option>');

});

关于javascript - 从另一个下拉列表填充下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com