客户端
<script type="text/html" id="ptpl">
<option>请选择省份</option>
{{each province}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<script type="text/html" id="ctpl">
<option>请选择城市</option>
{{each city}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<script>
//获取元素
var province = document.querySelector('#province');
var city = document.querySelector('#city');
var area = document.querySelector('#area');
//从接口获取省份信息
ajax({
url: 'http://localhost:3000/province',
success: function (data) {
//将服务器返回的数据和html进行拼接
var html = template('ptpl', { province: data });
//将拼接好的html字符串显示在页面中
province.innerHTML = html;
}
})
//为省份下拉框添加值改变事件
province.addEventListener('change', function () {
//根据省份id获取城市信息
var pid = this.value;
ajax({
url: '/cities',
data: {
id: pid,
},
success: function (data) {
var html = template('ctpl', { city: data });
city.innerHTML = html;
console.log(111);
}
})
})
</script>
服务器端
//省市联动
//1.省份信息响应
app.get('/province', (req, res) => {
res.send([{
id: '001',
name: '河南省',
}, {
id: '002',
name: '河北省',
}, {
id: '003',
name: '广东省',
}, {
id: '004',
name: '广西省',
}]);
})
//2.市信息响应
app.get('/cities', (req, res) => {
// 获取省份id
const id = req.query.id;
// 城市信息
const cities = {
'001': [{
id: '300',
name: '信阳市'
}, {
id: '301',
name: '南阳市'
}, {
id: '302',
name: '洛阳市'
}, {
id: '303',
name: '安市'
}],
'002': [{
id: '400',
name: '石家庄市'
}, {
id: '401',
name: '唐山市'
}, {
id: '402',
name: '秦皇岛市'
}, {
id: '403',
name: '邯郸市'
}],
'003': [{
id: '500',
name: '广州市'
}, {
id: '501',
name: '深圳市'
}, {
id: '502',
name: '佛山市'
}, {
id: '503',
name: '东莞市'
}],
'004': [{
id: '600',
name: '百色市'
}, {
id: '601',
name: '南宁市'
}, {
id: '602',
name: '北海市'
}, {
id: '603',
name: '柳州市'
}]
};
res.send(cities[id]);
});
问题: