我已经使用ajax和javascript在html中创建了一个搜索框。 结果是从数据库中加载的,键入该单词时,该单词显示在下面,当我们单击显示的单词时,该单词将插入搜索框,而没有任何反应。
html
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Including jQuery is required. -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!-- Including our scripting file. -->
<script type="text/javascript" src="script.js"></script>
<!-- Including CSS file. -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Search box. -->
<input type="text" id="search" placeholder="Search" />
<br>
<br />
<!-- Suggestions will be displayed in below div. -->
<div id="display"></div>
</body>
</html>
ajax
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
$Name = $_POST['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
echo '
<ul>
';
//Fetching result from database.
while ($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<!-- Creating unordered list items.
Calling javascript function named as "fill" found in "script.js" file.
By passing fetched result as parameter. -->
<li onclick='fill("<?php echo $Result['Name']; ?>")'>
<a>
<!-- Assigning searched result in "Search box" in "search.php" file. -->
<?php echo $Result['Name']; ?>
</li></a>
<!-- Below php code is just for closing parenthesis. Don't be confused. -->
<?php
}}
?>
</ul>
javascript
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "search.php" file.
$('#search').val(Value);
//Hiding "display" div in "search.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "search.php" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "search.php" file.
$("#display").html("");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
type: "POST",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
//Assigning result to "display" div in "search.php" file.
$("#display").html(html).show();
}
});
}
});
});
当我们开始搜索时,搜索框如下所示
然后,当我们单击显示的任何单词(例如第二个单词)时,它将被插入搜索框,如下所示:
我想使该单词可点击,而不是将其添加到搜索框中。谁能编辑我的代码
答案 0 :(得分:1)
将文本放在<?php session_start(); ?>
标记中,而不仅仅是在<li>
中。
<a>
然后将您的<ul>
<li>
<a href="#">David Copperfield</a>
</li>
<li>
<a href="#">Cristiano Ronaldo</a>
</li>
</ul>
事件附加到链接。