简体   繁体   中英

Array of array from mysql to populate selects for cities in countries

I currently have a webpage with two select drop downs. The top one is populated with countries, and when one is selected, the second select is then populated with major cities for that country.

Currently MySQL is used to get all records from a countries table to populate the first select, and after one is selected an ajax call is used to get the results from a MySQL query of the cities table, using a where clause to only return cities for the chosen country.

How would I go about this without requiring an ajax call for each change of country? And also without having to run a query for every country?

You can select all countries including major cities with a join:

SELECT * FROM countries, cities WHERE cities.country_id = countries.id

You can temporarily store the data in Javascript as a JSON object

var data = JSON.parse("<?php echo json_encode($mysql_result); ?>");

On change of the dropdown you can search the data object and return the cities for the second dropdown:

changeDropdown = function( country ){
    var cities = new Array();
    for( var i = 0; i < data.length; i++ ){
        if( data[i].country == country ){
            cities.push(data[i].cityName);
        }
    }
    return cities;
}

Naturally the code above depends on your datamodel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM