动态下拉更新基于另一个下拉列表

时间:2013-04-10 04:38:35

标签: php ajax json

我希望有人可以帮助引导我朝着正确的方向前进。我目前有一个文件,我将其称为data.php。在这个文件中,我有以下数据:

$sports_arr = array();
$sports_arr[] = "Basketball";
$sports_arr[] = "Baseball";
$sports_arr[] = "Football";

我在同一个data.php文件中也有以下数组:

$position = array();
$position['Basketball'][] = "Power Forward";
$position['Basketball'][] = "Small Forward";
$position['Basketball'][] = "Center";
$position['Soccer'][] = "Center Forward";
$position['Soccer'][] = "Right Wing";
$position['Soccer'][] = "Left Wing";
$position['Football'][] = "Halfback";
$position['Football'][] = "Fullback";
$position['Football'][] = "Wide Reciever";
$position['Football'][] = "Tight End";
$position['Football'][] = "Center";

问题是我想弄清楚如何获得第一个下拉列表,目前正在填充以下代码:

<div class="selectStyled">
    <select name="Sport1" class="styled">
    <option id="default" value="">Your Sport</option>
        <?php natsort($sports_arr);
        foreach ($sports_arr as $key => $val) { 
            echo "<option value='" . $val . "' id='position" . $key . "'>" . $val . "</option>";
        } ?>
    </select>
</div>

这是我遇到问题的地方。我想要的是基于上面的下拉结果(例如用户选择棒球),我想要第二个后续下拉以填充正确的位置数组。因此,如果他们选择篮球,它将立即和动态地与篮球位置一起填充页面上的第二个下拉。如果他们改变主意并选择足球,它将动态填充第二次下注与足球位置。

此处的任何帮助表示赞赏。我正在打一个主要的路障...谢谢!!

2 个答案:

答案 0 :(得分:2)

请尝试:

<?php
$sports_arr = array();
$sports_arr[] = "Basketball";
$sports_arr[] = "Baseball";
$sports_arr[] = "Football";

$position = array();
$position['Basketball'][] = "Power Forward";
$position['Basketball'][] = "Small Forward";
$position['Basketball'][] = "Center";
$position['Soccer'][] = "Center Forward";
$position['Soccer'][] = "Right Wing";
$position['Soccer'][] = "Left Wing";
$position['Football'][] = "Halfback";
$position['Football'][] = "Fullback";
$position['Football'][] = "Wide Reciever";
$position['Football'][] = "Tight End";
$position['Football'][] = "Center";
?>

<div class="home">
    <select id="s1">
        <?php foreach($sports_arr as $sa) { ?>
        <option value="<?php echo $sa; ?>"><?php echo $sa; ?></option>
        <?php } ?>
    </select>
    <select id="s2">
    </select>
</div>

<script type="text/javascript">
var s1= document.getElementById("s1");
var s2 = document.getElementById("s2");
onchange(); //Change options after page load
s1.onchange = onchange; // change options when s1 is changed

function onchange() {
    <?php foreach ($sports_arr as $sa) {?>
        if (s1.value == '<?php echo $sa; ?>') {
            option_html = "";
            <?php if (isset($position[$sa])) { ?> // Make sure position is exist
                <?php foreach ($position[$sa] as $value) { ?>
                    option_html += "<option><?php echo $value; ?></option>";
                <?php } ?>
            <?php } ?>
            s2.innerHTML = option_html;
        }
    <?php } ?>
}
</script>

大多数时候,人们使用ajax,但如果你的网络很慢,那么ajax就不是好办法。

答案 1 :(得分:0)

如果用户从第一个下拉菜单中选择篮球,则需要第二个下拉列表显示篮球阵列的所有记录。

所以你应该在第一次下拉的onChange()事件中使用AJAX函数。