Home > Article > Web Front-end > How to use JavaScript to achieve linkage between provinces and cities
This article mainly introduces in detail how to solve the bugs in the process of realizing provincial and municipal linkage through JavaScript. It has certain reference value. Interested friends can refer to it.
First, implement the provincial and municipal linkage. Describe the problems encountered
1.1. Original idea
1.1.1. Initialize loading of provinces
$.ajax({ 'type' : 'POST', 'dataType' : 'json', 'url' : '${rc.contextPath}/crm/merchantMgr/editMerchantBankAccount.htm?method=getBankProvinces', 'success' : function(msg) { bankProvinces = msg; for(var i=0;i<bankProvinces.length;i++){ $("#key_DSGAprovince").append("<option value='"+bankProvinces[i][0]+"'>"+bankProvinces[i][0]+"</option>"); } }, 'cache' : false, 'async' : false });
1.1.2. Load cities when clicking on provinces
function getBankCitys(){ $("#key_DSGAcity").empty(); var DSGAprovince=$("#key_DSGAprovince option:selected").text(); $.ajax({ 'type':'POST', 'data': {"province":DSGAprovince}, 'dataType': 'json', 'url':'${rc.contextPath}/crm/merchantMgr/editMerchantBankAccount.htm?method=getBankCities', 'success' : function(msg) { cities = msg; for(var i=0;i<cities.length;i++){ $("#key_DSGAcity").append("<option value='"+cities[i][0]+"'>"+cities[i][0]+"</option>"); } }, }); }
1.1.3. Problems
When loading, there is no problem and linkage can be achieved, but when echoing, cities cannot be loaded, but provinces can be loaded.
var tVal = '海南省'; if(tVal!=""){$("#key_DSGAprovince").val(tVal);} var tVal = '文昌'; if(tVal!=""){$("#key_DSGAcity").val(tVal);}
1.1.4. Analysis
This is because during initialization, only the provinces are loaded, and if(tVal!=""){$("#key_DSGAcity"). val(tVal);} This sentence means that the city’s option must be placed on the page before the value can be retrieved.
1.1.5. Solution
var DSGAprovince = '${myObj.DSGAprovince?default("请选择")}'; $.ajax({ 'type':'POST', 'data': {"province":DSGAprovince}, 'dataType': 'json', 'url':'${rc.contextPath}/crm/merchantMgr/editMerchantBankAccount.htm?method=getBankCities', 'success' : function(msg) { cities = msg; for(var i=0;i<cities.length;i++){ $("#key_DSGAcity").append("<option value='"+cities[i][0]+"'>"+cities[i][0]+"</option>"); } }, 'cache':false, 'async':false, });
Just load it once according to the province during initialization.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Responsive principles in Vue (detailed tutorial)
How to implement timestamp and date format using js Conversion between
In vue.js, the default route is not loaded
The above is the detailed content of How to use JavaScript to achieve linkage between provinces and cities. For more information, please follow other related articles on the PHP Chinese website!