javascript - 下拉列表未从数据库填充

标签 javascript php html mysql ajax

我好像遇到了问题。我有一个输入字段和一个 <select> field 。我需要在输入字段中输入一个位置,如果该单词与我的数据库中的记录匹配,那么它应该是我的 <select> 中的人员姓名下拉列表。这是我的 index.php 文件:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input type="text" name="location_input" id="location_input">
Tutor:<select name="locations" id="locations">
    <script> 
        $("#location_input").keyup(function(){
            const location = $("#location_input").val();
            $("#locations").html(''); //reset dropdown
            // do ajax call to get locations
            $.ajax({
                url: 'search.php',  //replace this with your route of the search function
                data: {location}, //pass location as body data
                dataType: 'json', //expect a json response back
                success: function(data) {
                    data.forEach(function(el) { //loop over the json response
                        let option = `<option id=${el.id} value=${el.name}>${el.name}</option>`
                        $("#locations").append(option); //append locations to select dropdown
                    });
                },
                error: function(err) {  //error functions
                    console.log(err);
                    alert("Error")
                }
            });
        });
    </script>

</select>
</body>
</html>

这是我的 search.php 文件:

   <?php
function SearchLocations() {
    $conn = new mysqli('localhost', 'root', '', 'tutors') or die ('Cannot connect to db');
    $result = $conn->query("select * from tutor_location where Location_tags LIKE ='%". $_GET['location']."%'");

    $locations = [];

    while ($row = $result->fetch_assoc()) {
        $locations[] = $row;    

    }

    return json_encode($locations);

}

?>

这是我的数据库的屏幕截图:enter image description here 我面临的问题是它给了我 localhost says error并且控制台没有向我显示错误。

最佳答案

您可以尝试像下面的请求一样使用ajax,

$.ajax({
      type:"POST",
      dataType:"json",
      url: 'search.php',
      data: {order_numbers: values, order_state: status},
      success: function(response){ },
      error: function(response){}
    });

关于javascript - 下拉列表未从数据库填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54216837/

相关文章:

javascript - 当列表中存在重复值时显示警报消息

javascript - 使用angularjs在ionic1中为http请求设置超时

javascript - 如何将对象名称添加到表列

javascript - 如何将 observableArray 中的 observable 复制到另一个 observableArray?

php - Yii - 使用关系中定义的范围的关系

php - 根据自定义帖子类型匹配/查询自动填充结帐输入

php - 统计一些有限的单词并显示它们与他们的名字相对应

javascript - 如何在 div 中动态生成可放置/可拖动/可排序的 div 元素?

javascript - 您如何监控选择标签?

Javascript - 如何将 jQuery 对象(表)传递给 Web Worker?