从mySQL表或CSV表

时间:2016-02-01 12:20:58

标签: mysql html5

对于网络注册表格,我需要询问该国家/地区。为此,我想在select元素中提供一个包含大约300个条目的给定列表。

从mySQL数据库表或CSV文件访问列表更快更有意义吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试将国家/地区列表存储为缓存的json文件,因为此列表可能不会发生太大变化。您可以编写一个脚本,以便每当更新国家/地区的数据库表时,它都会将其写入json文件。并且您可以使用本地存储来防止在第一页加载后重新下载json缓存文件:

<强> jQuery的:

$(document).ready(function(){

    // check to see if the list is already cached
    // if not download and store in local storage cache
    if(localStorage.getItem('list_country') === null)
    {
        $.get(
             '/cache/list_country.json'
            ,function(data){
                localStorage.setItem('list_country', JSON.stringify(data));
            }
        );
    }

    // use the stored cache to populate the select list
    $.each($.parseJSON(localStorage.getItem('list_country')), function(k, v){
        $('#country').append($('<option>').val(k).text(v));
    });
}

<强> HTML:

<select id="country">
    <option value="" selected disabled>Please Select</option>
</select>

PHP (更新缓存文件)

// list is key/value pairs from SELECT id, name FROM database table like
$list = array("US"=>"United States","FR"=>"France"); //etc

$file_path = $_SERVER['DOCUMENT_ROOT'].'/cache/list_country.json';
$handle = fopen($file_path.$this->cache_file, 'w');
fwrite($handle, json_encode($list));
fclose($handle);

<强> JSON

{"US":"United States","FR":"France"} // etc