城市下拉列表未填充



我正在尝试将城市动态加载到HTML中的select标记中。我可以选择州,然后我想通过ajax调用加载城市。

就控制台记录返回的数据而言,我一直纠结于如何将其加载到select选项标记中。请帮忙。

<select name="state" class="state">
<option value="" selected disabled>Choose State</option>
<?php foreach ($states as $state) {
echo "<option value='".$state->id."'>$state->name";
}?>
</select>
<select name="city" class="city" id="city">
<option value="" selected disabled>Choose City</option>
</select>
$.ajax({
type: "POST",
url: "includes/get_city.php",
data: {
state: selectedState
},
}).done(function(data) {
console.log(data); // Works when I console log
//Don 't know if this is the way
$('#city' > option).each(data, function(index, value) {
});
}

如果您的ajax响应与代码中的states集合相似,那么您可以使用

var toAppend = '';
$.each(data, function(index, city){
toAppend += '<option value="'+city.id+'">'+city.name+'</option>';
});
$('#city').append(toAppend );  

试试这个(假设索引和值以正确的方式使用(:

var text = '';
$.each(data, function(index, value){
text += '<option value="'+index+'">'+value+'</option>';
});
$('#city').html(text);
// or you can use append to put value in select
$('#city').append(text);

如果您正在获得json响应,请尝试以下操作:

$.ajax({
type: "POST",
url: "includes/get_city.php",
data: {
state: selectedState
},
dataType: "json"
}).done(function(data) {
$.each(JSON.parse(data), function () {
$('#city').append('<option  value="'+data.id+'">'+data.name+'</option>');
});
});

这个代码

$('#city' > option).each(data, function(index, value) 

将不起作用,因为不是附加"选项",而是搜索现有的

如果您有语法错误或其他,您也可以从chrome调试它(按F12(以进行检查

在线观看了一段视频,并认为这是一种方法。

$('#state').change(function() {
var state_id = $('#state').val();
$.ajax({
url: 'includes/get_city.php',
method: 'post',
data: 'state_id=' + state_id
}).done(function(cities) {
console.log(cities);
cities = JSON.parse(cities);
$('#city').empty();
cities.forEach(function(city) {
$('#city').append('<option>' + city.name + '</option>');
})
});
});

感谢所有的答案。

最新更新