douyu4535 2013-08-15 07:16
浏览 14
已采纳

根据其他选择选项从DB中选择选项

I have a form that has two select fields, one representing the region and one the name of the city/village/etc. I have a database with all these entries in the following form:

id (int 11, ai)
region (varchar 50) 
city(varchar 50)

I've found a script here on so that lets you select different options but it's made with JS and I have no idea how to adapt it to my needs. I need a database because I have 13.000+ entries and it's not really a good idea to enter them manually in the code. Here is the link to the topic that I've read, it's solution is in one of the comments as well.

how to change a selections options based on another select option selected?.

Please let me know if I need to edit my post before downrating. Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doujuyang1764 2013-08-15 07:31
    关注

    Just use ajax for this, when one select change fetch data from the server to feed other select.

    <select class="select_one">
    <?php /* render first select ?>
    </select>
    <select class="select_two"></select>
    <script>
    $(function() {
    
        $('.select_one').change(function() {
           var select = $('.select_two').empty();
           $.get('script.php', {region: $(this).val()}, function(result) {
               $.each(result, function(i, item) {
                   $('<option value="' + item.value + '">' + item.name + '</option>').
                       appendTo(select);
               });
           });
        });
    });
    </script>
    

    and you script.php should return JSON from db:

    if (isset($_GET['region'])) {
        $sql = new mysqli('localhost','username','password','database');
        $region = mysqli_real_escape_string($sql,$_GET['region']);
        $query = "SELECT * FROM cities WHERE region = $region";
        $ret = $sql->query($query);
        $result = array();
        while ($row = $ret->fetch_assoc()) {
             $result[] = array(
                 'value' => $row['id'],
                 'name' => $row['city']
             );
        }
        echo json_encode($result);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致