我正在尝试创建一个实时搜索栏,当单击建议时会打开结果,但是我不知道如何通过javascript将表单数据提交到php页面,该页面会根据单击的建议生成页面。 到目前为止,搜索栏将建议显示为链接,但显示的是所有项目,而不只是一个
JAVASCRIPT代码和搜索表
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
// $(document).on("click", ".result p", function(){
// $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
// $(this).parent(".result").empty();
});
//});
</script>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search for liquor..." />
<div class="result"></div>
</div>
</body>
可以查询的PHP代码
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "charles", "shoppingcartdemo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$term = mysqli_real_escape_string($link, $_REQUEST["term"]);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM shopping_items WHERE item_name LIKE '" . $term . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($rows = mysqli_fetch_array($result)){
$linka = "profile.php";
$resulta = $rows["item_name"];
echo " <p> <a href= " .$linka. "> $resulta </a> </p> " ;
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
所以
答案 0 :(得分:1)
在backend-search.php中,我将格式化返回的项目,如下所示:
<input type = “submit” name = “sub-with-link” value = “whatever the innerHTML of the link is”>
然后,在查询代码中,我将使用类似以下的内容:
$submit_term = $_REQUEST[‘sub-with-link’];
if ($submit_term != “”) {
$term = $submit_term;
} else {
$term = $_REQUEST[‘term’];
}
顺便说一句,我尚未对此进行测试,也不确定100%是否可行,但是我已经处理过类似的问题。如果这行不通,请告诉我
答案 1 :(得分:0)
这是另一种方法。链接不必打开页面,只需使它们调用如下函数即可:
<a onclick =“change_submit(this) href =“#”>...<\a>
这是js代码
function change_submit(data) {
Input(use a selector, the input does not have an id currently.value = data.innerHTML;
Form(use a selector, form should exist but apparently doesn’t).submit;
}