首页 > 解决方案 > 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();
?>

任何帮助将不胜感激。

标签: javascriptphpjquery

解决方案


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

推荐阅读