gpt4 book ai didi

javascript - 选择选项在更改时从 ajax 生成值

转载 作者:可可西里 更新时间:2023-11-01 12:53:16 24 4
gpt4 key购买 nike

我有here我的项目的代码和流程我有 3 在这里选择一个大陆一个国家一个城市我从 ajax 请求中获取数据来填充这些选择它现在工作正常我只是想有点花哨所以我想要一个几个功能

1.当大陆选择该大陆的国家列表时,当变化发生时,该大陆列表中列出了我想要这座城市 还显示当前该国第一个条目的城市 它没有发生我做的是我仍然需要更改条目 在国家选择显示城市列表

2.问题是我是否需要在大陆的 ajax 请求中添加另一个 ajax 请求我不确定这个是否可行我试过了,它现在不工作

Ajax 代码

$('.continentname').change(function() {
var id = $(this).find(':selected')[0].id;
//alert(id);
$.ajax({
type:'POST',
url:'../include/continent.php',
data:{'id':id},
success:function(data){
// the next thing you want to do
var country= document.getElementById('country');
$(country).empty();
var city = document.getElementById('city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(country).append('<option id=' + data[i].sysid + ' value=' + data[i].name + '>' + data[i].name + '</option>');
}
}
});

});

$('.countryname').change(function() {
var id = $(this).find(':selected')[0].id;
$.ajax({
type:'POST',
url:'../include/country.php',
data:{'id':id},
success:function(data){
// the next thing you want to do
var city = document.getElementById('city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(city).append('<option id=' + data[i].sysid + ' value=' + data[i].name + '>' + data[i].name + '</option>');
}
}
});

});

我从数据库中将值放入选项选择中

$("#continent").val(continentid);
$("#continent").change();
$("#country").change();
$("#country").val(countryid);
$("#city").val(cityid);

最佳答案

您可以在国家元素填充后触发更改事件

$('.continentname').change(function () {
var id = $(this).find(':selected')[0].id;
//alert(id);
$.ajax({
type: 'POST',
url: '../include/continent.php',
data: {
'id': id
},
success: function (data) {
// the next thing you want to do
var $country = $('#country');
$country.empty();
$('#city').empty();
for (var i = 0; i < data.length; i++) {
$country.append('<option id=' + data[i].sysid + ' value=' + data[i].name + '>' + data[i].name + '</option>');
}

//manually trigger a change event for the contry so that the change handler will get triggered
$country.change();
}
});

});

$('.countryname').change(function () {
var id = $(this).find(':selected')[0].id;
$.ajax({
type: 'POST',
url: '../include/country.php',
data: {
'id': id
},
success: function (data) {
// the next thing you want to do
var $city = $('#city');
$city.empty();
for (var i = 0; i < data.length; i++) {
$city.append('<option id=' + data[i].sysid + ' value=' + data[i].name + '>' + data[i].name + '</option>');
}
}
});
});

关于javascript - 选择选项在更改时从 ajax 生成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28059029/

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