无法进行现场ajax搜索工作

时间:2014-03-01 13:42:59

标签: javascript php html ajax

我是网络开发的新手抱歉,但我没有遇到问题

我刚刚创建了这个并且它不起作用。请帮助我不知道是什么问题。我没有得到任何结果。

但如果我去search.php它会显示所有名字。

HTML

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<input type="text" onKeyup="getName(this.value)"/><br>
<div id="result"></div>

<script type="text/javascript">

function getName(value){

$.post("search.php", {partialName:value}, function(data){

$("#result").html(data);

});

}

</script>

PHP(search.php中)

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

$partialName = $_POST['partialName'];

$query = "SELECT Name FROM Members WHERE Name LIKE '%$partialName%'";
$names = mysqli_query($dbc, $query);

while($namesArray = mysqli_fetch_array($names)){

echo "<div>".$namesArray['Name']."</div>";

}


?>

2 个答案:

答案 0 :(得分:1)

HTML:

<input type="text" id="search"/><br>

JS:

$("#search").on("keyup", function()
{
    var value = $(this).val();
    $.ajax({
        url: "search.php",
        type: "POST",
        data: "partialName="+value,
        success: function(data)
        {
            $("#result").html(data);
        }
    });
});

编辑:就像说明一样,可能值得逃避MySQL查询的输入:

$partialName = mysqli_real_escape_string( $_POST['partialName'] );

答案 1 :(得分:0)

<input type="text" id="search" /><br>
<div id="result"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('#search').keyup(function(){
        var name = $('#search').val();
        var datastring = "partialName="+name;
        $.ajax({
            url: "search.php",
            type: "POST",
            data: datastring,
            success: function(data)
            {
                $("#result").html(data);
            }
        });
    });
});
</script>

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

$partialName = $_POST['partialName'];

$query = "SELECT Name FROM Members WHERE Name LIKE '%".$partialName."%' ";
$names = mysqli_query($dbc, $query);

while($namesArray = mysqli_fetch_array($names)){

echo "<div>".$namesArray['Name']."</div>";

}

?>