我正在尝试将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>
答案 0 :(得分:0)
<script>
$(document).ready(function(){
$("#list1").change(function(){
var selected = this.value;
$.post("my.php", { choice: selected }, function(data){
alert(data);
});
});
});
</script>
#
中的$("#list1")
小意味着该元素的 id 应该匹配。
<select name="list1" .....
将其更改为<select name="list1" id="list1".....>
答案 1 :(得分:0)
仅在js函数触发时设置$_POST
超全局,即当您从下拉列表中选择某些内容时。否则仍然是空的。
您可以使用print_r($_POST)
通常,我使用实用程序方法从数组中检索数据:
function arrGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
返回键的值或默认值。用法如:
if(arrGet($_POST, 'choice')){
//do something
}
希望这会有所帮助......