PHP JSON响应包括HTML布局 [英] PHP JSON Response Includes HTML Layout
本文介绍了PHP JSON响应包括HTML布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里遇到问题:我正在尝试创建jQuery/AJAX/PHP实时搜索栏.我打电话给search.php
很好,但是每当我在控制台中输出响应时,我都会得到我的master.php
文件(只是站点范围的布局)的内容以及JSON编码的结果.我不知道是什么原因导致了这种情况的发生.
I'm struggling with an issue here: I'm trying to create a jQuery/AJAX/PHP live search bar. 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. I can't figure out what is causing this to happen.
这是我的jQuery:
Here is my 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().
像这样:
Write an exit() after the echo in search.php.
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.
这篇关于PHP JSON响应包括HTML布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文