我尝试根据在其他选择菜单上选择的值填充选择菜单。
到目前为止,我设法获得了值,我的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();
}
}
答案 0 :(得分:0)
这样做并确保您的服务器代码完全返回您要填写的键和值。
$.each(a,function(key, value) // a or jsondata
{
$select.append('<option value=' + key + '>' + value + '</option>');
});