原生js用ajax編寫省市聯動,二級聯動
阿新 • • 發佈:2018-12-22
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>城市聯動</title> </head> <body> <select name="china" id="q"> <option value="">西安</option> </select> <select name="china" id="w"> <option value="">西安</option> </select> </body> </html>
連結js部分
function ajax1809byJSONandDefault(obj) { let defaultObj = { "url":"#", "method":"get", "param":"", "isAsync":true, "func":null }; for(let key in obj){ defaultObj[key] = obj[key]; } //1、建立物件 let xhr = new XMLHttpRequest(); //2、設定請求引數 let urlAndParam = defaultObj.url; if(defaultObj.method.toLowerCase()=="get"){ urlAndParam+="?"+defaultObj.param; } xhr.open(defaultObj.method,urlAndParam,defaultObj.isAsync); //3、設定回撥函式 xhr.onreadystatechange = function(){ if(xhr.readyState==4 && xhr.status==200){ defaultObj.func(xhr.responseText); } } //4、傳送請求 if(defaultObj.method.toLowerCase()=="post"){ xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(defaultObj.param); }else{ xhr.send(); } }
<script type="text/javascript" src="js/ajaxtools.js"></script> <script> window.onload = function (){ getData(); $("q").onchange = function(){ showCity(this.value); } } function func(str){ console.log(str); } function getData(){ ajax1809byJSONandDefault({ "url":"json/city.json", "func":function(str){ showProvince(str); showCity($("q").value); } }); } let sheng function showProvince(str){ let data = JSON.parse(str); sheng = data.城市程式碼; let htmlstr = ""; for(let i in sheng){ htmlstr += `<option value="${sheng[i].省}">${sheng[i].省}</option>`; } $("q").innerHTML = htmlstr; } function showCity(str){ let citys; let htmlstr = ""; // alert("f"); for(let i in sheng){ if(sheng[i].省 == str){ citys = sheng[i].市; } } for(let j in citys){ htmlstr += `<option value="${citys[j].編號}">${citys[j].市名}</option>`; } $("w").innerHTML = htmlstr; } function $(id){ return document.getElementById(id); } </script>