javascript - editableSelect() 在 ajax 方法之后不会触发
问题描述
我有一个 ajax 方法,该方法在页面加载后立即运行,无需监听任何事件。ajax 从数据库中获取学生 ID 并在选择框中显示学生 ID。我希望选择框是可编辑的(http://indrimuska.github.io/jquery-editable-select/)。The function $('#studentID').editableSelect();
runs completely fine when the options are hardcoded in the select tag. 但是,当$('#studentID').editableSelect();
被调用并且从数据库中获取数据时,选择框中不会显示任何数据。
这是编写在 JavaScript 文件中的代码
$('#studentID').editableSelect();
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
}
});
#studentID
定义
<label for="studentID">ID</label>
<select id = "studentID" class="form-control">
</select>
php代码
<?php
$connection = new mysqli ("127.0.0.1", "root", "", "test");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$query = "SELECT `SID` FROM `student` ORDER BY `SID` ";
$result1= mysqli_query($connection, $query);
while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;
$connection->close();
?>
任何帮助将不胜感激。
解决方案
将editableSelect
移入ajax.success
方法中。问题是您正在初始化一个空的选择元素,然后使用异步ajax
方法将选项插入它。成功加载数据后将永远发生,然后您可以使用任何框架/库初始化选择,包括editableSelect
您想要的。
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
let student_el = $('#studentID');
student_el.html(html);
student_el.editableSelect();
}
});
编辑:
您可能没有以正确的方式包含该库,因此无论如何,这里有两种包含它的方法:
头部标签内
<head>
<!--Include jQuery + you libraries...-->
<script src="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet" />
</head>
在ajax调用内部
$.ajax({
type: 'POST',
url: './public/api/studentID.php',
success: function(html){
let student_el = $('#studentID');
student_el.html(html);
$.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js")
.then(() => {
student_el.editableSelect(); // Call this function after the script have been successfully loaded.
});
//student_el.editableSelect();
}
});
推荐阅读
- c# - 统一从图库中选择多个图像
- java - 如何从网络选项卡中的 DOM 结构中获取承载令牌 - 使用 Selenium?
- phalcon - Phalcon - 如何组织 RESTFul 应用程序
- firebase - 无法将哈希映射值作为 ArrayList
- javascript - 无法通过 webdriverI-O 启动浏览器
- mysql - 检查密码是否正确,在数据库中对 md5 进行哈希处理
- javascript - 如何避免在 javascript 中使用 Media Recorder 录制滞后
- c++ - 结构成员的长列表
- jquery - 如何使用名称属性添加输入值?
- python - Pyinstaller 可执行文件仅适用于激活的虚拟环境