我这里有我的项目的代码和流程,我有 3 个在这里选择一个大陆 一个用于国家 1 对于城市,我获取数据以填充这些 从 Ajax 请求中选择它现在工作正常 我只是想做一点花哨,所以我想有一些功能
1.当选择大陆时,该大陆的国家列表列在更改发生时的国家列表中 我想要城市 还显示当前该国第一个条目的城市 我没有发生我所做的是我仍然需要更改条目 在国家/地区中选择以显示城市列表
2.问题是我是否需要在大陆的 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>');
}
}
});
});
您可以在../include/continent.php
中获取第一个国家/地区的国家/地区列表和城市列表:
- 获取国家/地区列表数组
- 获取城市列表,其中国家/地区 ID = 国家/地区[0].id
- 将它们组合并添加另一个字段,例如
type
例:
type | sysid | name
country | 1 | America
country | 2 | Canada
city | 1 | New York
city | 2 | Los Angles
然后在javascript中:
$.post("../include/continet.php", {"id":id}, function(data){
$(country).empty();
$(city).empty();
for (var i = 0; i < data.length; i++) {
if(data[i].type == "country"){
$(country).append...
}
else{
$(city).append...
}
}
});