javascript - editableSelect() 在 ajax 方法后不会触发

标签 javascript php jquery

我有一个 ajax 方法,该方法在页面加载后立即运行,而不监听任何事件。 ajax 从数据库中获取学生 ID 并在选择框中显示学生 ID。我希望选择框可编辑( http://indrimuska.github.io/jquery-editable-select/ )。当选项被硬编码在 select 标记中时,函数 $('#studentID').editableSelect(); 运行完全正常。但是,当调用 $('#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 方法中。问题是您正在初始化一个空的 select 元素,然后使用异步 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 标签内

<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();
    }
});

关于javascript - editableSelect() 在 ajax 方法后不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52562889/

相关文章:

javascript - 为什么这不是四舍五入(Javascript)?

php - 如何从远程服务器自动提交(POST)表单?

php - AjaxFileUpload 插件无法检索 $_POST 数据

javascript - 如何使用 Enter 键按下按钮

javascript - jQuery Toggle Navigation Bar 使用 Div

javascript - 使用PHP保存未知文件名的文件

javascript - JQuery 日期选择器 : put week number in the input box instead of selected day

Jquery super 盒子

javascript - 使 div 类随页面向下 float 的问题

javascript - 根据滚动位置突出显示链接