[英]PHP JSON Response Includes HTML Layout
I'm struggling with an issue here: I'm trying to create a jQuery/AJAX/PHP live search bar. 我在这里遇到一个问题:我正在尝试创建jQuery / AJAX / PHP实时搜索栏。 I am calling search.php
fine, but whenever I output the response in the console, I get the contents of my master.php
file (which is just site-wide layout) along with the JSON-encoded results. 我称search.php
很好,但是每当我在控制台中输出响应时,我都会获得master.php
文件(只是站点范围的布局)的内容以及JSON编码的结果。 I can't figure out what is causing this to happen. 我不知道是什么原因导致了这种情况的发生。
Here is my jQuery: 这是我的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;
});
});
And search.php
: 和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);
Thanks! 谢谢!
Write an exit() after the echo in search.php. 在search.php中的回显之后写一个exit()。
Like this: 像这样:
$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();
It should prevent showing the entire page. 它应该防止显示整个页面。
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..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.