[英]How do I use PHP to populate a second select-tag with options based on the option selected in the first select-tag?
I will draw the options for the second select-tag from a database. 我将从数据库中为第二个选择标签绘制选项。
Thanks. 谢谢。
Non-javascript solution: 非JavaScript解决方案:
Have the user submit the form that the select is in, so the values would be in GET/POST. 让用户提交选择所在的表单,因此值将在GET / POST中。
When the page appears again, PHP can access the variables to assemble the second select tag. 当页面再次出现时,PHP可以访问变量以组合第二个select标签。
Something like this: 像这样:
<form action='' method='post'>
<select name='select1'>
<option value='blah'>blah</option>
</select>
<?PHP if(isset($_POST['select1']) {
/* call DB and get infos */
echo "<select>";
/* FOR loop echoing <option>info</option> */
echo "</select>"; ?>
</form>
Haven't tested it but should be OK ish. 还没有测试过,但应该可以。
There is no need to use Ajax at all if the tables are small. 如果表很小,则根本不需要使用Ajax。 You can just build every possible second select box and hide it on the page and display the appropriate one based on the user's selection. 您只需构建每个可能的第二选择框,然后将其隐藏在页面上,然后根据用户的选择显示相应的选择框即可。 This is even faster than Ajax and requires no page reloads or http requests. 这甚至比Ajax更快,并且不需要页面重新加载或http请求。
If the tables are too large, though, or the second select box can have user-dependent data, then that is obviously not an option. 但是,如果表太大,或者第二个选择框可以包含用户相关的数据,那么显然这不是一个选择。
you have to use ajax to perform this without page submit. 您必须使用ajax来执行此操作,而无需提交页面。
Or just submit the page make the action self (the same php). 或者只是提交页面使动作自行(相同的php)。
check if there is $_POST[select1value] 检查是否有$ _POST [select1value]
then populate from db in second select 然后在第二选择中从数据库填充
<select2>
<?php
if( ($_POST['submit']) && ($_POST['select1']) )
{
?>
<option1> of select2</option>
<?
}
?>
Thats it. 而已。
But AJAX is nice if you wan to use 但是如果您想使用AJAX很好
Typically you have one table for each select box. 通常,每个选择框都有一个表。 Here's an example: 这是一个例子:
table1:
id | item | extra_info
1 | 1 | ...
2 | 2 | ...
... ... ...
table2:
id | prev_choice | item
1 | 1 | 1_a
2 | 1 | 1_b
3 | 2 | 2_a
4 | 2 | 2_b
... ... ...
This way you just search for any item in table2 with a "prev_choice" based on whatever was selected before. 这样,您就可以根据之前选择的内容使用“ prev_choice”搜索table2中的任何项目。 For instance, if table one contained a list of continents, table two could contain a list of countries where "prev_choice" refers to which continent that country is within. 例如,如果表一包含一个大陆列表,则表二可以包含一个国家列表,其中“ prev_choice”指该国家所在的大陆。
The SQL query would look something like: SQL查询如下所示:
SELECT * FROM table2 WHERE prev_choice LIKE {$_GET["selected"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.