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;
JSON에서 HTML로 출력 형식을 지정하는 경우 jQuery 코드에서 json을 구문 분석하고 배열의 각 json 객체에 대해 루프를 반복하고 HTML을 페이지에 동적으로 추가해야합니다.
if(searchTitle) {
$.ajax({
type: "POST",
url: "getBooks.php",
data: data,
success: function(res)
{
var my_table="<table>";
$.each(res, function(i, obj){
my_table+="<tr> <td> "+obj.clumn_name+" </td> <td> "+obj.clumn_name2+" </td> </tr> ";
});
my_table+"</table>";
$("#search_results").html(my_table);
}
});
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다