javascript - 如何在 Laravel 8 中使用输入的值在不刷新页面或提交表单的情况下在同一页面上呈现特定内容
问题描述
我正在尝试建立一个学生目录。我有一个结构,它包含在类-> 组-> 学生中。我的数据库中已经有了类和组。每个组属于一个类。例如,我进入我的班级页面并创建班级 1。之后,我进入我的群组页面并添加一个分配有班级 1 的群组“A”。我可以为每个班级添加多个组。现在我想在我的学生页面上创建一个学生。为此,我想将学生添加到特定组中。为了能够选择组,管理员必须首先从选择下拉列表中选择类。选择类后,下一个选择将仅呈现分配给所选类的组。
我现在的解决方案是使用用户在第一个下拉列表中选择的类 id 设置 $_GET 超级全局。我通过带有 window.location.href url 更改的 javascript 函数来做到这一点。我将组下拉列表的逻辑设置为在呈现选项之前查找 $_GET 变量。我不认为这是一种干净且好的方法,因为在重置位置并且始终重置输入值时,页面总是会刷新。
我只想使用用户从类下拉列表中选择的任何内容来呈现组下拉列表中的选项。关于这个问题,Laravel 8 的内置功能可以为我做些什么吗?
作为我现在正在做的事情的一个例子:
<select name="classes" id="classes" onchange="getClassID()"> // getClassID just changes the location and adds the selected class id to the url as a query string
@php
foreach ($classes as $class) {
if(isset($_GET['classID'])){
if($_GET['classID']*1 === $class->id){
echo " <option value={$class->id} selected>{$class->classes_number}</option>";
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
}
@endphp
</select>
<script>
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let option = document.getElementById("classes").value;
window.location.href='/students/create?classID=' + option;
}
</script>
<select name="group_id" id="group">
@php
// If the user has changed the initial classes select dropdown value, we will
// get all of the groups that have the class that was selected and display them
// as options in this select
if(isset($_GET['classID'])){
$classID = $_GET['classID']*1;
foreach ($groups as $group) {
if ($group->classes_id === $classID) {
echo "<option value={$group->id}>{$group->group_name}</option>";
}
}
}
else {//another code that handles the situation in which all classes are erased}
@endphp
</select>
解决方案
您可以通过 api 获取选项并在客户端创建第二个选择,而不是重新加载页面。
var groupIdSelect = document.getElementById('group');
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let classID = document.getElementById("classes").value;
fetch('api/students/create?classID=' + classID)
.then((res) => res.json())
.then((groups) => {
for (group of groups) {
if (group.classes_id === classID) {
var option = document.createElement('option');
option.value = group.id
option.textContent = group.group_name;
groupIdSelect.appendChild(option);
}
}
})
}
推荐阅读
- postgresql - Postgresql 选择基于另一个带有 order、limit 和 agregate 的选择
- javascript - 持久化 Redux 存储的正确架构及其重置
- arrays - 将数组添加到列表视图
- macos - 将组从用户更改为root
- azure-devops - Azure Devpos:如何手动部署特定版本?
- css - 如果 list-style-position 设置为 inside,如何防止列表项在项目符号后立即断开?
- javascript - QuerySelectorAll 一个类不包含样式属性?
- django - 日期验证 --> 结束日期必须大于开始日期
- http - 如何使用 SRV 记录指向 80 以外的端口
- javascript - 需要这些样式的面板在数据输入后改变颜色