我正在尝试创建一个Ajax实时搜索,但Ajax调用返回完整的HTML而不是我正在寻找的用户名。我尝试过程序而不是PDO,它工作得非常好,但我试图保持我的整个项目PDO。我不太确定是什么原因导致它发送HTML而不是预期的结果。我在控制台中也没有收到任何错误。谢谢你的帮助。
$("#check-input").keyup(function() {
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".check-input-result");
if (inputVal.length) {
$.get("php_backend/backend-search.php", {
term: inputVal
}).done(function(data) {
resultDropdown.html(data);
});
} else {
resultDropdown.empty();
}
});
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
try{
if(isset($_REQUEST['term'])){
$sql = "SELECT * FROM users WHERE username LIKE :term";
$stmt = $pdo->prepare($sql);
$term = $_REQUEST['term'] . '%';
$stmt->bindParam(':term', $term);
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row['username'] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
unset($stmt);
unset($pdo);
?>
答案 0 :(得分:0)
而不是echo
使用return
来发送数据(没有任何HTML)。
$data = [];
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
array_push($row['username']);
}
}
return $data;
遍历.done()
方法中的数据并添加必要的html进行显示。