我好像遇到了问题。我有一个输入字段和一个 <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);
}
?>
这是我的数据库的屏幕截图:
我面临的问题是它给了我 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/