PHP JSON响应包括HTML布局


PHP JSON Response Includes HTML Layout

我在这里遇到了一个问题:我试图创建一个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);

谢谢!

在search.php的回显语句后写入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();

它应该防止显示整个页面。

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..