JQuery即时搜索:如何发出第二个post请求.以及如何利用输入键进行搜索


JQuery instant search: how to make a second post request. and how to make a use enter key to search

我使用JQuery创建了一个类似于google搜索的即时搜索。

Q1。post到search.php使用搜索函数searchq()然后打印出返回的结果工作正常,但是create_object.php不能得到变量txt(已经成功地post到search.php),关于如何修复它的任何想法?第二季我想创建一个函数,允许用户被定向到第一个搜索结果(这是锚定的url),当按下输入,任何想法如何实现这一点?我尝试了一些东西,但很快就变成了一场混乱的噩梦。

注意,这里没有包含连接到数据库的函数。因为我认为数据库的用户名和密码设置和你的不一样。所以请在search.php中创建您自己的来测试它。在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",{createVal: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);
    }
?>

我只是在你的HTML中做了一个简单的改变。我删除了onkeyup attr,并添加了id,以便有更简单的jQuery选择器

<form method="POST">
    <input type="text" name="search" id="search" style="width:400px " placeholder="Search box">
    <input type="submit" value=">>">
    <div id="output">
    </div>
</form>
<script>
    $(document).ready(function() {
        var request;
        $("#search").on("keyup", function(e) {
            if(e.which === 13) {
                // Q2 -> Enter pressed
                var firstResult = $("#output").find("a").first();
                if(firstResult.length === 1) { // Just checking there is a result
                    window.location = firstResult.attr("href");
                }
                return false; // This prevents the form to submit
            } else {
                // Any other key
                searchq();
            }
        });
    });
</script>

更新

不能从createq函数访问txt变量的原因是因为它是searchq函数的本地变量,这意味着在searchq函数之外根本不存在。

最简单的解决方案是这样做:

var txt;
function searchq() {
    // Some code here
    // Use txt, not var txt
}
function createq() {
    // Some code here
    // Use txt, not var txt
}
新更新

searchq()中使用

$("#search_output")

但应该是

$("#output")

您还在search.php中打印格式错误的HTML代码。应该是这样的

$output.="<div><a href='##'>".$object_name."</a></div>";
// Note the missing > in the <a> tag

我对PHP不太熟悉,所以无法测试实际场景。但就javascript代码而言,请在末尾检查以下内容:

Q1:您可能将函数名'createq'拼错为'creatq'

    ... <div id='"create'" onclick='"creatq() ...
    ..
    ..
    function createq(){
    ..
    }

Q2键盘上的每个键都分配了一个键码。对于enter key,它的值是13。您可以通过在任何事件处理程序函数中使用event.which来获得它。
在这种情况下,它可以在输入字段的keyup or keypress上获取,应该像下面这样做:

$(document).on('keyup keypress', 'input[name=search]', function(evt) {
    if (evt.which === 13) {
       // find the first search result in DOM and trigger a click event 
       // $("#search_output").find('a').first().trigger('click');

      // OR
      // find the url of the 1st link and use document.location to redirect 
      var redirectUrl = $('#search_output').find('a').first().attr('href');
      document.location = redirectUrl;
    }
});