以2维数组来维护省市,首次加载全部省和第一个省对应的所有市,存在2维数组中,改变省时,如果2维数组中有对应的市就从数组中取,否则从后台取。
var array = new Array(); function getProvince(){ $.ajax( {type:"POST", url:"/getProvince.action", dataType:"json", async:false, success:function (json) { len = json.listp.length; for (var i = 0; i < len; i++) { array[i] = new Array(); array[i].id = json.listp[i].vcharProvId; array[i].name = json.listp[i].vcharProvince; } }} ); getCity(0); } function getCity(num){ $.ajax({type:"POST", url:"/getCity.action", data:{ID:array[num].id}, dataType:"json", async:false, success:function (json) { len = json.listc.length; for (var i = 0; i < len; i++) { array[num][i] = new Object(); array[num][i].id=json.listc[i].vcharCityId; array[num][i].name=json.listc[i].vcharCity; }} }); } $().ready(function(){ getProvince(); init(); }); function init(){ var province =""; for(var i=0;i<array.length;i++){ province +="<option value="+i+ ">"+array[i].name+"</option>"; } $("#province").append(province); var obj =new Object(); obj.value=0; select_city(obj); } function select_city(obj){ var i=obj.value; var city =""; if(array[i][0]==null){ getCity(i); } for(var j=0;j<array[i].length;j++){ city +="<option value="+array[i][j].id+">"+array[i][j].name+"</option>"; } $("#city").html(city); }
<select name="" id="province" οnchange="select_city(this)">
</select>
<select name="" id="city"></select>