简体   繁体   English

使用PHP JQuery和JSON进行动态下拉

[英]Dynamic drop down using PHP JQuery and JSON

I am trying to create a dynamic drop down menu using the data I parsed from a JSON file and stored in an array in PHP. 我正在尝试使用我从JSON文件解析并存储在PHP数组中的数据创建动态下拉菜单。 I am trying to use jquery to get the data but I do not know where I am going wrong. 我正在尝试使用jquery来获取数据,但我不知道我要去哪里错了。

    <?php require './index.php';
?>
<!DOCTYPE html><head><meta charset='UTF-8'> 
    <title>Dropdown</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script>
        $(function() {
        alert('<?php echo$city_list; ?>');
            $("#json-one").change(function() {

            var $dropdown = $(this);

                $.getJSON("demo2.php", function(data) {

                    var key = $dropdown.val();
                    var vals = [];
                    switch(key) {
                        case '<?php echo $city_list;?>':
                            vals = data.split(",");
                            break;}
                    var $jsontwo = $("#json-two");
                    $jsontwo.empty();
                    $.each(vals, function(index, value) {
                        $jsontwo.append("<option>" + value + "</option>");
                    });});});});
    </script></head><body>
    <div id="page-wrap">
            <h1>Pulls from JSON</h1>
        <select id="json-one">
            <option selected value="base">Please Select</option>
            <option value="id1"><?php echo $city_list;?></option>
                </select>
            <br />
            <select id="json-two">
            <option>Please choose from above</option>
        </select>
        </div></body></html>

I got data like $city_list which contains only one value at present. 我得到了像$city_list这样的数据,该数据目前仅包含一个值。

array.php array.php

<?php
require 'index.php';
header('Content-Type: application/json');
echo json_encode($list);

Output of this is [["Hil",[125,139]],["Mer",[52,52]]] . 其输出是[["Hil",[125,139]],["Mer",[52,52]]] Now what I was planning was when I select a city from the dropdown box the above hil and mer second dropdown should be created. 现在我正在计划的是,当我从下拉框中选择一个城市时,应该创建上述hilmer第二个下拉列表。 And if I select any of this their corresponding values should be displayed. 而且,如果我选择其中任何一个,则应显示其相应的值。

Any help on this would be appreciated. 任何帮助,将不胜感激。

在html标记中为其他下拉菜单创建Dom元素(即select及其容器),默认情况下将其隐藏,然后基于第一个选择添加选择选项(通过jquery),然后取消隐藏这些元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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