我正在尝试使用 jQuery 和 PHP 进行一些简单的 AJAX 搜索。但是我似乎无法让正确的搜索字符串发挥作用。我想按标题搜索,如果没有设置标题,则单击搜索时显示所有结果。另外,我想将结果显示为漂亮的 HTML,而不是以类似 JSON 的代码返回。类似于:
$book["title"]
$book["author"]
$book["description"]
SQL 设置:
表名称:书籍 表字段:id、标题、作者、描述
HTML:
<div id="search">
<form action="#">
<p><label for="title">Book Title:</label> <input type="text" id="search_title" name="search_title"></p>
<p><input type="submit" id="search_submit" name="search_submit" value="Search!"></p>
<p><em><small>For example A Game of Thrones or The Lord of the Rings</small></em></p>
<hr>
</form>
</div>
<div id="search_results">
</div>
<script>
$(document).ready(function() {
$("#search_submit").on("click", function() {
var searchTitle = $("#search_title").val(),
data = 'title=' + searchTitle;
if(searchTitle) {
$.ajax({
type: "POST",
url: "getBooks.php",
data: data,
success: function(res)
{
$("#search_results").html(res);
}
});
}
return false;
});
});
</script>
PHP:
if(isset($_GET["title"])) {
$title = $_GET["title"];
}
if(isset($title) && !empty($title)) {
$pdo_title = "WHERE title LIKE '%" . $title . "%'";
} else {
$pdo_title = "";
}
$pdo_books = "books";
$pdo = new PDO("mysql:dbname=removed;host=removed","removed","removed");
$statement = $pdo->prepare("SELECT * FROM $pdo_books $pdo_title");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
最佳答案
您已经提到了 ajax 中的 post 方法,并且您正在尝试使用 $title = $_GET["title"];
尝试使用
$title = $_POST["title"];
关于php - AJAX 搜索和 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515436/