我正在尝试使用另一个下拉框中的选项填充下拉框。我已经弄清楚如何使用数据库中的数据填充列表,似乎问题在于从同一页面上的第一个下拉框中选择他们所选择的内容而不提交表单。这是我到目前为止所做的。
<select name = "trainer_has_update_pokemon">
<p>Trainer</p>
<?php
$query = "SELECT name FROM Trainer";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()) {
echo"<option>$name</option>";
}
$stmt->close();
}
?>
</select>
<?php
$trainer_name = $_GET['trainer_has_update_pokemon'];
?>
<p>Pokemon</p>
<select name = "type_of_update_pokemon">
<?php
$query = "SELECT DISTINCT p.name FROM Pokemon p WHERE p.owner_id = (SELECT t.trainer_id FROM Trainer t WHERE t.name = '$trainer_name')";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($pkmn_name);
while ($stmt->fetch()) {
echo"<option>$pkmn_name</option>";
}
$stmt->close();
}
?>
我对Javascript或AJAX没有任何经验,所以如果有办法在没有这些的情况下做到这一点,那将会有所帮助,但如果没有,我愿意在这种情况下学习他们的应用程序。
答案 0 :(得分:1)
不幸的是,您需要某种客户端脚本来调用外部php页面,以便实时提取数据。快速模拟会看起来像:
的javascript:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){ //document ready
$('select[name="trainer_has_update_pokemon"]').change(function(){ // when trainer_has_update_pokemon changes
$.ajax({
type:"POST", //send a post method
url:'ajax.php', // path to ajax page
data:"trainer_name="+$(this).val(), //set trainer_name to value
success:function(response){ // retrieve response from php
$('select[name="type_of_update_pokemon"]').html(response); // update select
}
});
});
});
</script>
PHP(我已命名为ajax.php):
<?php
/* ADD YOUR DATABASE CONNECTION */
$trainer_name = $_POST['trainer_name']; // DONT FORGET TO ESCAPE!!
$query = "SELECT DISTINCT p.name FROM Pokemon p WHERE p.owner_id = (SELECT t.trainer_id FROM Trainer t WHERE t.name = '$trainer_name')";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($pkmn_name);
while ($stmt->fetch()) {
echo"<option>$pkmn_name</option>";
}
$stmt->close();
}?>