我在这里遇到问题:我正在尝试创建一个jQuery / AJAX / PHP实时搜索栏。我正在调用search.php
,但每当我在控制台中输出响应时,我都会获得master.php
文件的内容(这只是站点范围的布局)以及JSON编码的结果。我无法弄清楚导致这种情况发生的原因。
这是我的jQuery:
$(function() {
$("#search-text").keyup(function() {
var $res = $(".search-results");
$.ajax({
type: "POST",
url: "search.php",
data: { query: $(this).val() },
cache: false,
success: function(html) {
$res.show();
$res.append(html);
console.log(html);
},
error: function(xhr, status, error) {
console.log("XHR: " + xhr);
console.log("Status: " + status);
console.log("Error: " + error);
}
});
return false;
});
});
search.php
:
$key = $_POST["query"];
$db = new Database();
$db->query("SELECT * FROM users WHERE firstname LIKE :key OR lastname LIKE :key OR firstname AND lastname LIKE :key");
$db->bind(":key", '%' . $key . '%');
$rows = $db->resultset();
echo json_encode($rows);
谢谢!
答案 0 :(得分:3)
在search.php中的echo之后写一个exit() 像这样:
$key = $_POST["query"];
$db = new Database();
$db->query("SELECT * FROM users WHERE firstname LIKE :key OR lastname LIKE :key OR firstname AND lastname LIKE :key");
$db->bind(":key", '%' . $key . '%');
$rows = $db->resultset();
echo json_encode($rows);
exit();
它应该阻止显示整个页面。
答案 1 :(得分:0)
In search.php before sending $rows in json_encode() give one condition that will check $row is empty or not.like :
if(!empty($res))
echo json_encode(array('status'=>'success','result'=>$rows));
else
echo json_encode(array('status'=>'failed','result'=>[]));
In ajax check
success: function(html)
{
if(html.status=='success')
{
$res.show();
$res.append(result.html);
console.log(result.html);
}
}
may be it will work..