我想制作一个简单的搜索栏。搜索栏通过JQuery将数据发送到PHP(执行搜索)。数据通过回调函数发送回HTML。搜索功能正常运行。但是,每次输入搜索输入时,整个页面都会重复。我不知道为什么会这样做。正在从MySQL数据库中提取数据。
<?php
session_start();
include("connection/connection.php");
if(isset($_POST['search_term'])){
$search_term = mysqli_real_escape_string($db_connect,htmlentities($_POST['search_term']));
if(!empty($search_term)){
$sql_search = "SELECT first FROM students_register WHERE first LIKE '%$search_term%' ";
$result_search = $db_connect->query($sql_search);
$result_count = $result_search->num_rows;
$suffix = ($result_count != 1) ? 's' : '';
echo "<p>Your search for <strong>" .$search_term. " </strong>has returned <strong>".$result_count."</strong> result" .$suffix. "</p>";
while($results_row = $result_search->fetch_assoc()){
echo "<p><strong>".$results_row['first']."</strong></p>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
Search: <input id="search" name="search" placeholder="search">
<span id="search_display"></span>
</body>
<script type="text/javascript">
$("#search").keyup(function(){
var search_term = $(this).val();
$.post('test2.php', {search_term : search_term}, function(result){
$("#search_display").html(result);
});
});
</script>
</html>
``
答案 0 :(得分:-1)
我的问题是test2.php
,你的html页面也是同一页?
尝试两页,
<?php // test2.php
session_start();
include("connection/connection.php");
if(isset($_POST['search_term'])){
$search_term = mysqli_real_escape_string($db_connect,htmlentities($_POST['search_term']));
if(!empty($search_term)){
$sql_search = "SELECT first FROM students_register WHERE first LIKE '%$search_term%' ";
$result_search = $db_connect->query($sql_search);
$result_count = $result_search->num_rows;
$suffix = ($result_count != 1) ? 's' : '';
echo "<p>Your search for <strong>" .$search_term. " </strong>has returned <strong>".$result_count."</strong> result" .$suffix. "</p>";
while($results_row = $result_search->fetch_assoc()){
echo "<p><strong>".$results_row['first']."</strong></p>";
}
}
}
&GT?; 而Html包含另一个页面
<!DOCTYPE html>
<html>
<head>
<title>Index.html</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
Search: <input id="search" name="search" placeholder="search">
<span id="search_display"></span>
<script type="text/javascript">
$("#search").keyup(function(){
var search_term = $(this).val();
$.post('test2.php', {search_term : search_term}, function(result){
$("#search_display").html(result);
});
});
</script>
</html>
原因是,您正在从test2.php请求数据,test2.php也包含了html代码,因此只有它一次又一次地重新出现。请试试这个让我知道结果。