<body> <select name="" id="provinice"></select> / <select name="" id="city"></select> / <select name="" id="town"></select> </body> </html> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script src="./sendAjax.js"></script> <script> // 获取省份的数据,填充到 provinice 下拉列表中 async function fn() { let a = await sendAjax({ url: "http://cj.shenzhou888.com.cn/hb_vote/api.php?action=area&id=0" }) // console.log( a ); let str = "<option value='0'>请选择</option>"; for (let item of a.data) { str += `<option value="${item.id}">${item.name}</option>` } $("#provinice").html(str); } fn(); // 给省份下拉列表绑定事件 $("#provinice").on("click", async function () { // 获取到被点击的option的value值 // console.log( $("#provinice > option:selected").attr("value") ); let id = $("#provinice > option:selected").attr("value"); let b = await sendAjax({ url: "http://cj.shenzhou888.com.cn/hb_vote/api.php?action=area&id=" + id }) console.log(b); let str = "<option value='0'>请选择</option>"; for (let item of b.data) { str += `<option value="${item.id}">${item.name}</option>` } $("#city").html(str); }) //给市下拉列表绑定事件 $('#city').on('click', async function () { //获取市的到被点击的option的value值 let id = $('#city>option:selected').attr('value'); let town = await sendAjax({ url: 'http://cj.shenzhou888.com.cn/hb_vote/api.php?action=area&id=' + id }); // console.log(town); let str = '<option value="0">请选择</option>'; for (let item of town.data) { str += `<option value="${item.id}">${item.name}</option>`; $('#town').html(str) } })
封装的sendAjax.js:
// promise的封装函数 function sendAjax({type="get",url="",data=null,dataType="json"}) { return new Promise((reslove, reject) => { $.ajax({ type, url, data, dataType, success: function (response) { reslove(response) }, error(err) { reject(err) } }); }) }