多级联动
使用ajax传输(练习多级联动)
数据库建表语句:‘
CREATE TABLE `address` ( `ID` int(4) DEFAULT NULL, `ParentId` int(4) DEFAULT NULL, `name` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
使用servlet将数据以集合的形式存储,在转成json传输到前端(jdbc和servlet就不写了)
练习使用ajax
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body onload="ajaxTest(0,'stat')"> <div id="sel" name="sel"> <select id="stat" name="stat" onchange="ajaxTest(this.value,'city')" onfocus="ajaxTest(this.value,'city')"> </select> <select id="city" name="city" onchange="ajaxTest(this.value,'qu')" onfocus="ajaxTest(this.value,'qu')"></select> <select id="qu" name="qu" onchange="ajaxTest(this.value,'jiedao')" onfocus="ajaxTest(this.value,'jiedao')"></select> <select id="jiedao" name="jiedao"></select> </div> </body> </html> <script> function ajaxTest(pid,obj){ let request; // let stuts=document.getElementById("stat") let url = "/shen?pid="+pid ; if(window.XMLHttpRequest){ request=new XMLHttpRequest(); }else if(window.ActiveXObject){ request=new ActiveXObject("Msxml2.XML HTTP"); } request.open("Get", url); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.onreadystatechange = function () { if (request.readyState === 4) { if(request.status==200){ let ja=request.responseText; let date=JSON.parse(ja); let stat=document.getElementById(obj); // console.log(stat) for(let i=0;i<date.length;i++){ stat.options[i]=new Option(date[i].name,date[i].id); // address.textContent=stat.options[i].text; } } } } request.send(null); } </script>