自动完成下拉列表

时间:2016-10-11 14:15:08

标签: php jquery mysql

我有一个自动填充搜索栏来搜索员工姓名。

的index.php

<script>
        $(document).ready(function() {

            $('input.employees').typeahead({
                name: 'employees',
                remote: 'mysql.php?query=%QUERY'

            });

        })
    </script>
        <form><font color='black'>
            <input type="text" name="employees" class="employees" placeholder="Search Employees...">

Autocomplete.php

if (isset($_REQUEST['query'])) {
    $query = $_REQUEST['query'];
    $sql = mysql_query ("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE '%{$query}%' OR name_last LIKE '%{$query}%'");
    $array = array();
    while ($row = mysql_fetch_array($sql)) {
        $array[] = array (
            'label' => $row['name_first'].', '.$row['name_last'],
            'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',

        );
    }
    //RETURN JSON ARRAY
    echo json_encode ($array);
}

这很好用。但是,我希望能够在下拉列表中单击结果并转到另一个页面。这需要包含一个变量employee_id。 E.g http://example.com/new-page.php?id=employee_id

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery-ui自动完成小部件来完成。 添加jquery-ui的javascript和css文件后,编写如下代码:

$('.employees').autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST", 
                contentType: "application/json;charset=utf-8", 
                dataType: "json", 
                async: true,
                url: "Autocomplete.php",
                data: "{'query':'" + request.term + "'}",
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            value: item.value,
                            id: item.employee_id,
                            label:item.label
                        }
                    }))
                }
            })
        }
    }).data('ui-autocomplete')._renderItem = function (ul, item) {
        return $('<li></li>')
            .data('item.autocomplete', item)
            .append('<a href="yourPage.php?employee_id='+item.id+'">' + item.label + '</a>')
            .appendTo(ul);

}