我正在尝试将 js var 传递给 php var,然后使用该 php var 来遍历数组并填充下拉列表。我可以看到 php var 获得了正确的值,但 list2 和 list3 没有被填充。
如果我将字符串放在自己身上$list1 = 'somestring';
,它会起作用,但是当我使用$list1 = $_POST['choice'];
它时它不起作用。
<script>
$(document).ready(function(){
$("#list1").change(function(){
var selected = this.value;
$.post("my.php", { choice: selected }, function(data){
alert(data);
});
});
});
</script>
<?php
echo'
<form name="menu">
<div>
<select name="list1" size="1" onchange="setOptions(document.menu.list1.options
[document.menu.list1.selectedIndex].value,document.menu.list2,document.menu.list3);">
<option value=" " selected></option>
<option value="one">item1</option>
<option value="two">item2</option>
<option value="three">item3</option>
<option value="four">item4</option>
</select><br><br>
<select name="list2" size="1"onchange="setOptions(document.menu.list2.options
[document.menu.list2.selectedIndex].value,document.menu.list3,' ');">
<option value=" " selected>Select an option</option>
</select><br><br>
<select name="list3" size="1">
<option value=" " selected>Select an option</option>
</select><br>
</div>
</form>';
?>
下拉列表
<script>
function setOptions(chosen, selbox, selbox2)
{
selbox.options.length = 0;
if (chosen == " ")
{
selbox.options[selbox.options.length] = new Option('Select an option',' ');
selbox2.options[selbox2.options.length] = new Option("Select an option"," ");
setTimeout(setOptions(' ',document.menu.list3),5);
}
if (chosen == "one")
{
showList2(selbox);
}
if (chosen == "two")
{
showList2(selbox);
}
if (chosen == "three")
{
showList2(selbox);
}
if (chosen == "four")
{
showList2(selbox);
}
//some code snipped
}
function showList2(selbox)
{
<?php
$n = 0;
$list1 = $_POST['choice'];
foreach($list[$list1] as $key => $value)
{
$key_array[$n] = $key;
$Lname[$n] = $list[$list1][$key]['name'];
$n++;
}
$jsArray = json_encode($key_array);
echo "var jsKeys = ". $jsArray . ";";
$jsArray = json_encode($Lname);
echo "var jsNames = ". $jsArray . ";";
?>
for (var i=0;i<jsKeys.length;i++)
{
var result = selbox2.options[selbox2.options.length] = new Option(jsNames[i],jsKeys[i]);
if(i == jsKeys.length-1)
{
var result = setTimeout(setOptions(jsKeys[0],document.menu.list3,' '),5);
}
}
return(result);
}
</script>