0

我正在尝试在 ajax (jQuery) 的帮助下完成自动完成任务。让我们看看脚本

这是html =>

<input type="text" name="user_key" id="user_key">

这是同一个文件中的javascript =>

<script type="text/javascript">
$(function(){
    $("#user_key").autocomplete({
        source: function(request,response){
            var suggestions = [];
            $.ajax({
                url: "/ajax/autocomplete.php",
                type: "POST",
                data: {user_key:$(this).val()},
                success: function(result){
                    $.each(result,function(i,val){
                        suggestions.push(val.name);
                    });
                },
                dataType: "json"
            });
            response(suggestions);
        }
    });
});
</script>

这是来自 autocomplete.php 文件的 php 脚本 =>

if (!$connection->connect_errno){
        if ($connection->set_charset("utf8")){
            if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
                for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
                    if ($row = $r->fetch_assoc()){
                        $array[$x] = array("name",$row['name']);
                    }
                }
                $r->free();
            }
        }
    }
    echo json_encode($array);

PS。它不起作用。请帮助,过去 2 天我一直在尝试完成这项任务,但无法使其正常工作。预先感谢:)

4

2 回答 2

0

You need to take another look at the autocomplete docs but you will be able to find an answer here: jquery auto-suggestion example doesn't work

于 2012-08-03T15:45:49.160 回答
0
$array[$x] = array("name",$row['name']);

这使得数据库中的名称和值都作为 array() 的元素

将 autocomplete.php 的代码更改为

if (!$connection->connect_errno){
        if ($connection->set_charset("utf8")){
            if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
                for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
                    if ($row = $r->fetch_assoc()){
                        $array[$x] = array("name"=>$row['name']);
                    }
                }
                $r->free();
            }
        }
    }
    echo json_encode($array);

这将使 name 作为从数据库中获取的值的键

这会帮助你。

于 2012-08-03T13:00:09.850 回答