Ajax---案例(省市区联动)用到template()模块
红色为:引入的框架或模块
天蓝色为:tamplate模块
淡黄色为:tamplate语法
淡绿色为:获取html中的元素
淡橙色为:使用tamplate函数传值(返回模板数据),并将数据拼接到html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>省市区联动</title> <link rel="stylesheet" type="text/css" 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"> <option>请选择省份</option> </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 --> <script type="text/javascript" src="/js/ajax.js"></script> <script type="text/javascript" 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 type="text/javascript"> //获取省市区下拉框元素 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 Prohtml=template("provinceTpl",{province:data}); //console.log(Prohtml); //将拼接好的html字符串显示再页面中 province.innerHTML=Prohtml; } }); //为省份的下拉框添加值改变事件 province.onchange=function(){ //获取省份id var pid=this.value; //清空区下拉框中的数据 var html=template(‘areaTpl‘,{area:[]}); area.innerHTML=html; //根据省份id获取城市信息 ajax({ type:‘get‘, url:‘http://localhost:3000/cities‘, data:{ id:pid }, success:function(data){ //console.log(data); var Cityhtml=template("cityTpl",{city:data}); city.innerHTML=Cityhtml; } }) } //当用户选择城市的时候 city.onchange=function(){ //获取城市id var cid=this.value; //根据城市id 获取区信息 ajax({ type:‘get‘, url:‘/areas‘, data:{ id:cid }, success:function(result){ //console.log(result); var Areahtml=template("areaTpl",{area:result}); //console.log(Areahtml); area.innerHTML=Areahtml; } }) } </script> </body> </html>
接口文档截图:
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05