我使用ajax创建了一个实时搜索,效果非常好。但是问题是,我需要首先单击输入字段来显示所有列出的数据。原因可能是keyup
函数。我不知道用什么来代替它。我确实尝试过更改焦点等等,但ajax根本没有显示我的数据。我不熟悉ajax。
这是我的输入代码和ajax。
<p style="text-align: center">Enter your search here: <input type="text" id="search" name="search" placeholder="Enter your search here"> <b><i>ex: d1234567891.. hazwan.. etc.. </i></b></p>
<div id="result" class="login"></div>
<script type="text/javascript">
$(document).ready(function(e) {
$("#search").keyup(function() {
$("#result").show();
var x = $(this).val();
$.ajax({
type:'POST',
url:'res.php',
data:'q='+x,
cache:false,
success:function(data){
$("#result").html(data)
}
});
});
});
</script>
</div>
这是我的数据库代码和显示结果。
//print_r($_GET);
$q=$_POST['q'];
$query="SELECT *
FROM
viewlibrary
WHERE
studentname LIKE :q OR
matricno LIKE :q OR
title LIKE :q OR
programme LIKE :q OR
serialno LIKE :q
ORDER BY studentname ASC";
$stmt = $db->prepare($query);
$stmt->bindValue(':q','%'.$q.'%');
$stmt->execute();
$a = 0;
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Edit</th>";
echo "<th>Delete</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
echo "<tr align='center'><td>". ($a+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td><a href='editpage.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/edit-icon.png' width=15px></a></td><td><a href='deletepage.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/remove-icon-png-15.png' width=15px></a></td></tr>";
$a++;
}
echo "</tbody>";
echo "</table>";
}
else{
echo "<p align='center'>Nothing to show you :( I am really sorry for this T_T </p>";
}
?>
每当我对ajax代码进行编辑时,它就不再运行了。我试着在互联网上查找,但找不到适合ajax的。因此,我实际上想要的是显示页面加载时列出的所有数据,而不是在用户单击输入字段之后。
请帮忙。
您是否尝试过将ajax移动到一个单独的函数?
Ex。
function ajaxSearchUpdater(){
$("#result").show();
var x = $('#search').val();
$.ajax({
type:'POST',
url:'res.php',
data:'q='+x,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(); // your function call
}
}