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

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

本文介绍了根据其他选择选项从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)

我在这里找到了一个脚本这可以让你选择不同的选项,但它是用JS制作的,我不知道如何根据我的需要调整它。我需要一个数据库,因为我有13.000多个条目,并且在代码中手动输入它们并不是一个好主意。这是我读过的主题的链接,它的解决方案也在其中一条评论中。

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.

如果我需要在降级之前编辑我的帖子,请告诉我。在此先感谢!

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

推荐答案

当一个选择更改从服务器获取数据以提供其他选择时,只需使用ajax。 / p>

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>

而你 script.php 应返回JSON来自db:

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);
}

这篇关于根据其他选择选项从DB中选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 15:32