实现基于AJAX的级联下拉菜单 完整代码
时间: 2023-12-19 10:06:22 浏览: 138
下面是一个基于AJAX的级联下拉菜单的完整代码示例:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>基于AJAX的级联下拉菜单</title>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
$(document).ready(function(){
$("#province").change(function(){
var province_id = $(this).val();
$.ajax({
type: "POST",
url: "get_city.php",
data: {province_id: province_id},
dataType: "json",
success: function(data){
var city_html = "";
$.each(data, function(i, city){
city_html += "<option value='" + city.id + "'>" + city.name + "</option>";
});
$("#city").html(city_html);
}
});
});
});
</script>
</head>
<body>
<div>
<select id="province">
<option value="">请选择省份</option>
<option value="1">广东省</option>
<option value="2">北京市</option>
<option value="3">上海市</option>
</select>
</div>
<div>
<select id="city">
<option value="">请选择城市</option>
</select>
</div>
</body>
</html>
```
PHP代码(get_city.php):
```php
<?php
header('Content-Type: application/json; charset=utf-8');
$province_id = $_POST['province_id'];
if($province_id == 1){
$city_list = array(
array('id' => 1, 'name' => '广州市'),
array('id' => 2, 'name' => '深圳市'),
array('id' => 3, 'name' => '珠海市')
);
}elseif($province_id == 2){
$city_list = array(
array('id' => 4, 'name' => '北京市')
);
}elseif($province_id == 3){
$city_list = array(
array('id' => 5, 'name' => '上海市')
);
}else{
$city_list = array();
}
echo json_encode($city_list);
?>
```
这段代码实现了一个基于AJAX的级联下拉菜单,当用户选择一个省份时,通过AJAX请求PHP脚本get_city.php,获取该省份下的城市列表,并将城市列表渲染到第二个下拉菜单中,从而实现了级联效果。
阅读全文