如何实时显示搜索结果

时间:2014-02-24 19:03:28

标签: php html ajax

这里我有简单的搜索引擎来搜索用户名。当人们输入用户名时,我希望他们在搜索框下面看到结果,并且只有在他们点击输入后才会将其带到搜索页面(如facebooks搜索引擎)。

html

<div class="search">
<form action="search.php" method="GET">
<input type="text" name="Search" size="50">
<input type="submit" value="Search">
</form>
</div>

php(search.php)

<?php
require 'includes/connection.php';

$term = $_GET['Search'];

$query_ver = "select * from Members where Name like '%$term%'";
$query = mysqli_query($dbc, $query_ver);

while($row = mysqli_fetch_array($query)) {

    $name = $row['Name'];

}

echo $name;

?>

有没有办法只用php和html

在搜索框下方显示$ name

1 个答案:

答案 0 :(得分:0)

<强> HTML

<div class="search">
<form action="search.php" method="GET">
<input type="text" name="search" size="50" class="search">
<input type="submit" value="Search">
</form>
</div>

<强>的Javascript

<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
    $.ajax({
    type: "POST",
    url: "result.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find(\'.name\').html();
    var decoded = $("<div/>").html($name).text();
    $(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$(\'#searchid\').click(function(){
    jQuery("#result").fadeIn();
});
});
</script>

<强>的search.php

<?php
include('db.php');
if($_POST)
{
    $q = mysql_real_escape_string($_POST['search']);
    $strSQL_Result = mysql_query("select id,name,email from live_search where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
    while($row=mysql_fetch_array($strSQL_Result))
    {
        $username   = $row['name'];
        $email      = $row['email'];
        $b_username = '<strong>'.$q.'</strong>';
        $b_email    = '<strong>'.$q.'</strong>';
        $final_username = str_ireplace($q, $b_username, $username);
        $final_email = str_ireplace($q, $b_email, $email);
        ?>
            <div class="show" align="left">
                <img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span>&nbsp;<br/><?php echo $final_email; ?><br/>
            </div>
        <?php
    }
}
?>
  

供参考,这是一个很好的解决方案

LINK1 LINK2