我用 html 和 php/mysql 创建了一个简单的下拉菜单
<select name="location_id" id="location_id" class="form-control">
<?php
$sql = "SELECT * FROM locations";
$result = mysqli_query($conn, $sql);
while($row=mysqli_fetch_assoc($result)){ ?>
<option value="<?php echo $row['location_id'];?>">
<?php echo $row['location_name'];?></option>
<?php } ?>
</select>
在从另一页插入新记录之前,它工作得很好。我需要刷新页面才能在下拉列表中获取新插入的记录。
在我当前的应用程序中,每当用户单击下拉列表时,我都需要刷新下拉选项而不刷新整个页面。这些选项应该从 mysql 数据库中实时获取。
我已经搜索了解决方案,但找不到类似的解决方案。
最佳答案
要仅刷新页面的一部分,您需要使用 JavaScript,具体来说是 AJAX。
Ajax 允许您发送 HTTP 请求和更新页面元素,而无需重新加载整个页面。
你可以试试这样的东西
<script>
function refresh_items() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("location_id").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "refresh_list.php", true);
xhttp.send();
}
</script>
<select name="location_id" id="location_id" class="form-control" onclick="refresh_items();">
</select>
现在您已经制作了客户端脚本,您希望 refresh_list.php
上的服务器端 PHP 看起来像这样
<?php
//all your SQL settings and stuff here
$sql = "SELECT * FROM locations";
$result = mysqli_query($conn, $sql);
while($row=mysqli_fetch_assoc($result)){ ?>
<option value="<?php echo $row['location_id'];?>">
<?php echo $row['location_name'];?></option>
<?php } ?>
关于php - 每当用户单击下拉列表时刷新下拉选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55510952/