Devbridge JQuery Autocomplete不使用serviceUrl

时间:2016-04-19 17:58:26

标签: javascript php jquery jquery-autocomplete

我正在尝试实现devBridge自动完成功能,但它不适用于ajax。当我使用没有php的手动json对象但我需要从数据库中获取数据时它可以工作。 PHP代码:

 <?php
require_once "medoo.php";
$database = new medoo([
    'database_type' => 'mysql',
    'database_name' => 'elektriksikayet',
    'server' => 'localhost',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
    'port' => '3307'
]);
$return_arr = [];
$keyword =  $_POST['keyword'];
$companies = $database->select('companies','company_name');
foreach ($companies as $comp){
    $row_array['label'] = $comp;
    array_push($return_arr, $row_array);
}
echo json_encode($return_arr);
?>

HTML CODE:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery.js"></script>
    <script src="js/jquery-autocomplete.js"></script>
    <script src="js/companyAutoComplete.js"></script>
</head>
<body>
<input type="text" id="autocomplete"/>
</body>
</html>

JS CODE

$(document).ready(function () {
    $("#autocomplete").autocomplete({
        serviceUrl:'AutoComplete.php', //tell the script where to send requests
        //callback just to show it's working
        onSelect: function(value){ alert('You selected: ' + value); }
    });
});

2 个答案:

答案 0 :(得分:2)

您的回复应该是有效的JSON和以下格式:

   {
        suggestions: [
            { "value": "United Arab Emirates", "data": "AE" },
            { "value": "United Kingdom",       "data": "UK" },
            { "value": "United States",        "data": "US" }
        ]
    }

您返回的内容似乎没有这种结构。

答案 1 :(得分:1)

对于其他有相同问题的人: 您应该以这种方式管理响应:

$("#autocomplete").autocomplete({
        serviceUrl:'AutoComplete.php'
        transformResult: function (response) {
                return {
                    suggestions: $.map(response, function(dataItem) {
                        return { value: dataItem.name, data: dataItem };
                    })
                };
            },
        });