我使用JQuery创建了一个类似于google搜索的即时搜索。
Q1。post到search.php使用搜索函数searchq()然后打印出返回的结果工作得很好,但是createq()函数根本不工作,当我使用alert()进行测试时,它没有触发,关于如何修复它的任何想法,因此变量txt可以post到create_object.php(已成功post到search.php)。
第二季我想创建一个函数,允许用户直接到第一个搜索结果(这是锚定的url),当输入按下,任何想法如何实现这一点?我尝试了一些东西,但是它搞砸了。
注意,这里没有包含连接到数据库的函数。因为我认为数据库的用户名和密码设置和你的不一样。所以如果你想测试它,请创建你自己的。在mysql中设置了一个名为"objects"的表,它有一列名为"name"。
提前感谢!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id='"create'" onclick='"creatq()'"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP文件(search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php文件(create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
两个问题合一!
Q1:问题似乎是onclick函数中的拼写错误:
onclick='"creatq()'"
应该onclick='"createq()'"
Q2:按enter键将提交表单,因此您使用submit处理程序捕获enter键,然后重定向:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(大部分工作都归功于这个答案)