Ajax 的 Devbridge AutoComplete 不填写建议

Devbridge AutoComplete with Ajax doesn't fill suggestions

我有一个自动完成字段,它会触发服务器在数据库中搜索全名并返回 JSON 响应。

当我使用本地数组时它工作正常,但是当我使用 JSON 服务器响应时,建议列表不会更新,即使响应在网络控制台中看起来是正确的(据我所知)。

我的控制台没有错误,这不是 CSS 问题,因为当我检查代码时,建议 div 是空的。

这是我的 html 输入字段:

<input type="text" id="form_fullname" name="form[fullname]" required="required" class="contact-select form-control" autocomplete="off" data-cip-id="form_fullname">

这是自动完成建议 div:

<div class="autocomplete-suggestions" style="position: absolute; display: none; max-height: 300px; z-index: 9999;"></div>

这是我的 js:

$('.contact-select').autocomplete({
    serviceUrl: 'contacts/search/fullname/',
    minChars: 3,
    deferRequestBy: 200
})

这是一个 JSON 响应(在 JSONLint 上验证):

{"query":"vial-","suggestions":["VIAL-COLLET, Bastien"]}

哎哟...我在 ajaxComplete 回调中添加了我的自动完成方法...不知道为什么! 它现在运行良好。

我正在使用相同的自动完成插件,一切正常,除了建议列表不会在用户键入时更新。整个列表就出现在那里。

这是我的 JS 代码:

`$('#searchName').autocomplete({
        serviceUrl: "getfoodname.php",
        minChars: 2,
        onSelect: function (suggestion) {
                //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                window.open("/detail.php?MonAnID="+suggestion.data,"_self")
                }
            });`

这是我的 PHP 代码

`include 'dbconnection.php';
    // Check connection
    if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
    } 

    $keyword = $_GET['query'];

    //Build final SQL statement to search
    $selectsql = "SELECT MonAnID, MonAnName FROM ListMonAn WHERE MonAnName LIKE '%".$keyword."%'";
    //Display data to table
    $result = $conn->query($selectsql);

    $suggestions = array();

    if ($result->num_rows > 0) {
         // output data of each row
        while($row = $result->fetch_assoc()) {  

                $foodname = $row["MonAnName"];
                $foodid = $row["MonAnID"];  

                $suggestions[] = array(
                "value" => $foodname,
                "data" => $foodid
                );
            }       
    }

    echo json_encode(array(
        'query' => $keyword,
        'suggestions' => $suggestions));
    conn.close();`

我有同样的症状,这对我来说已经解决了。

这是我之前的

$(document).ajaxComplete(function () {
    $('#SelectedInput').autocomplete({
        serviceUrl: '/AutoComplete/' + $('#SelectedInput').attr('data-autocomplete-action'),
        dataType: 'json'
    });
});

这是我得到的结果

$(document).ajaxComplete(function (event, xhr, options) {
    var modalLoadUrl = '/MyController/GetModalContent';
    if (options.url == modalLoadUrl) {
        $('#SelectedInput').autocomplete({
            serviceUrl: '/AutoComplete/' + $(el).attr('data-autocomplete-action'),
            dataType: 'json'
        });
    }
});

我哪里出错了:每次我打开模式时,我都在动态加载“SelectedInput”和 ajax 调用。然后我在 ajax 完成函数中设置了自动完成功能。然而,每次我使用 ajax 搜索自动完成的查询时,这也会触发,这导致每次我输入新内容时搜索都会重置。

我是如何修复它的:我需要做的就是将自动完成方法放在 if 语句中,检查请求的 url 是否与 url 匹配,以便 ajax 调用加载页。现在,自动完成方法仅在加载模式时运行一次。