The example in this article describes the method of jquery retrieving json data to achieve province and city cascading. Share it with everyone for your reference. The details are as follows:
Using jQuery mobile as a framework for creating mobile web requires realizing the function of province and city cascading. The specific code is as follows (there are still areas that need optimization):
Html code:
In jQuery mobile, there is an input list attribute, followed by the
<input id="province" list="prvlist" placeholder="省/自治区/直辖市" onblur="changeProvince();"> <datalist id="prvlist"> </datalist> <input id="city" list="citylist" placeholder="市" onblur="changeCity();"> <datalist id="citylist"> </datalist> <input id="area" list="arealist" placeholder="区"> <datalist id="arealist"> </datalist>
js code:
js code, main functions
1. Extract json data and bind it to the provincial drop-down list
2. After the provincial input is selected, the municipal list will be automatically bound
3. The district level drop-down list is the same as the city level
<script> $(function () { getProvince(); //页面打开后,省级下拉列表自动绑定 }) //获取省份 function getProvince() { var Aid; var Afather; $.get('area_json0.txt', {}, function (data) { for (var i = 0; i < data.length; i++) { if (data[i].fatherId == 0) { Afather += '<option id=" ' + data[i].id + '" value="' + data[i].name + '">'; } } $("#prvlist").append(Afather); } , 'json'); } function changeProvince(){ var city; var prv_val=$("#province").val(); getJson(prv_val); } function changeCity(){ var city_val=$("#city").val(); getJsonArea(city_val); } function getJson(Name){ var cityID; $.get('area_json0.txt', {}, function (data) { for (var i = 0; i < data.length; i++) { if (data[i].name == Name) { cityID=data[i].id; } } setCity(cityID); } , 'json'); } function setCity(val){ var Acity; var $listcity=$("#citylist"); $.get('area_json0.txt', {}, function (data) { for (var n = 0; n < data.length; n++) { if (data[n].fatherId == val) { alert(data[n].id); Acity += '<option id=" ' + data[n].id + '" value="' + data[n].name + '">'; } } $listcity.append(Acity); } , 'json'); } function getJsonArea(Name){ var areaID; $.get('area_json0.txt', {}, function (data) { for (var i = 0; i < data.length; i++) { if (data[i].name == Name) { areaID=data[i].id; } } setArea(areaID); } , 'json'); } function setArea(Aval){ var Aarea; var $listarea=$("#arealist"); $.get('area_json0.txt', {}, function (data) { for (var m = 0; m < data.length; m++) { if (data[m].fatherId == Aval) { alert(data[n].id); Aarea += '<option id=" ' + data[m].id + '" value="' + data[m].name + '">'; } } $listarea.append(Aarea); } , 'json'); } </script>
The code should be further optimized, so save the code for now.