案例:省市區三級關聯(ajax)
步驟
- 通過接口擷取省份資訊
- 使用JavaScript擷取到省市區下拉框元素
- 将伺服器端傳回的省份資訊顯示在下拉框中
- 為下拉框元素添加表單值改變事件(onchange)
- 當使用者選擇省份時,根據省份id擷取城市資訊
- 當使用者選擇城市時,根據城市id擷取縣城資訊
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>搜尋框輸入文字自動提示</title>
<link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
<style type="text/css">
.container {
padding-top: 150px;
}
</style>
</head>
<body>
<div class="container">
<div class="form-inline">
<div class="form-group">
<select class="form-control" id="province"></select>
</div>
<div class="form-group">
<select class="form-control" id="city">
<option>請選擇城市</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="area">
<option>請選擇縣城</option>
</select>
</div>
</div>
</div>
<script src="/js/ajax.js"></script>
<script src="/js/template-web.js"></script>
<!-- 省份模闆 -->
<script type="text/html" id="provinceTpl">
<option>請選擇省份</option>
{{each province}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<!-- 城市模闆 -->
<script type="text/html" id="cityTpl">
<option>請選擇城市</option>
{{each city}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<!-- 縣城模闆 -->
<script type="text/html" id="areaTpl">
<option>請選擇縣城</option>
{{each area}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<script>
// 擷取省市區下拉框元素
var province = document.getElementById('province');
var city = document.getElementById('city');
var area = document.getElementById('area');
// 擷取省份資訊
ajax({
type: 'get',
url: 'http://localhost:3000/province',
success: function (data) {
// 将伺服器端傳回的資料和html進行拼接
var html = template('provinceTpl', {province: data});
// 将拼接好的html字元串顯示在頁面中
province.innerHTML = html;
}
});
// 為省份的下拉框添加值改變事件
province.onchange = function () {
// 擷取省份id
var pid = this.value;
// 清空縣城下拉框中的資料
var html = template('areaTpl', {area: []});
area.innerHTML = html;
// 根據省份id擷取城市資訊
ajax({
type: 'get',
url: '/cities',
data: {
id: pid
},
success: function (data) {
var html = template('cityTpl', {city: data});
city.innerHTML = html;
}
})
};
// 當使用者選擇城市的時候
city.onchange = function () {
// 擷取城市id
var cid = this.value;
// 根據城市id擷取縣城資訊
ajax({
type: 'get',
url: 'http://localhost:3000/areas',
data: {
id: cid
},
success: function(data) {
var html = template('areaTpl', {area: data});
area.innerHTML = html;
}
})
}
</script>
</body>
</html>