我创建了一个类似于谷歌搜索使用JQuery的即时搜索。突出显示的代码不起作用。这是奇怪的,因为他们自己的工作很好,其他一切正常工作。任何想法为什么发生这种情况? Q1。 searchq()工作正常,但createq()函数不起作用,变量txt可以发布到其他文件(search.php)。但是,函数createq()不能POST。它在测试后得到了全局变量txt,但是无论使用什么POST方法,php文件(create_object.php)都无法得到它。任何人都可以帮助写一些可以在我的代码中工作的POST代码。Javascript两个奇怪的问题:POST不工作,window.location.href不工作
Q2 我想创建一个函数,当按下回车键时,用户将被重定向到第一个搜索结果(用一个url来锚定)。为了达到这个目的,我创建了一个函数,让变量redirectUrl将锚定的url作为字符串获取,但是,重定向函数window.location.href不起作用,页面只是刷新了。我通过自己在另一个文件中测试了window.location.href函数,它虽然工作。这很奇怪,我的网页只是刷新,它甚至刷新,当我直接到谷歌。 window.location.href( “www.google.com”)。
请注意,我没有在这里包括连接到数据库功能。因为我认为数据库的用户名和密码设置与您的不同,所以如果您想测试它,请自行创建。 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" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_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: test if the txt has got by the createq function
alert(txt);
**$.post("create_object.php",{creatVal:txt});**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</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);
}
?>
您不应将多个问题作为一个问题发布,这会减少获得答案的机会。 – regular
'** $。post'在函数'createq' - 我猜控制台中有错误当你加载页面 – RamRaider
没有错误在控制台 – raichuchu