当我在表单输入中键入字母时,数据库中图片的名称不会出现。我正在尝试在页面上实施实时搜索。我得到了名为'pinterest'的MySql数据库,其中的表'pictures'和'picture_name'列具有不同的图片名称。我希望在表单输入中输入字母时显示这些名称。什么也没做:-(
我有MySql数据库,php表单和ajax请求。
文件:search.php:
require_once __DIR__.'/connect.php';
?>
<form id="frmSearch" method="post" action="search.php">
<label>Pickup location <br>
<input type="text" name="txtSearchPictureName" id="txtSearchPictureName" placeholder="Search.." list="searchList" required>
<datalist id="searchList"></datalist>
</label>
</form>
<script src="search.js"></script>
文件:search.js
$('#txtSearchPictureName').on('input', function(val){
$.ajax({
method : "GET",
url : 'apis/api-search-picture.php?txtSearchPictureName='+val.target.value,
cache: false,
dataType:"JSON"
}).
done( function(jData){
$('#searchList').empty()
jData.forEach(x => {
$('#searchList').append('<option value="' + x.picture_name + '"></option>')
})
}).
fail( function(){
})
})
文件:api-search-picture.php
<?php
//connection do db
require_once __DIR__.'/connect.php';
$sPictureName = $_GET['txtSearchPictureName'];
try{
$stmt = $db->prepare('SELECT picture_name FROM pictures WHERE picture_name LIKE :sPictureName ');
$stmt->bindValue(':sPictureName', "%$sPictureName%");
$stmt->execute();
$aRows = $stmt->fetchAll();
echo json_encode($aRows);
} catch(PDOEXception $ex){
echo $ex;
}
```