【问题标题】:Autocomplete from remote datasource doesn't give any suggestions来自远程数据源的自动完成没有给出任何建议
【发布时间】:2018-05-21 14:53:02
【问题描述】:

根据表单缩小自动完成建议的范围。事情是我能够将过滤器发送到服务器;这也给出了正确的输出,但它最终不会作为文本区域中的建议(自动完成)。

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Combined</title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <style>
            .ui-autocomplete-category {
                font-weight: bold;
                padding: .2em .4em;
                margin: .8em 0 .2em;
                line-height: 1.5;
            }

            .ui-autocomplete {
                max-height: 100px;
                overflow-y: auto;
                /* prevent horizontal scrollbar */
                overflow-x: auto;
            }

            .ui-autocomplete-loading {
                background: white url("../img/ui-anim.gif") right center no-repeat;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
            $(function () {
                $.widget("custom.catcomplete", $.ui.autocomplete, {
                    _create: function () {
                        this._super();
                        this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
                    },
                    _renderMenu: function (ul, items) {
                        var that = this,
                                currentCategory = "";
                        $.each(items, function (index, item) {
                            var li;
                            if (item.event != currentCategory) {
                                ul.append("<li class='ui-autocomplete-category'>" + item.event + "</li>");
                                currentCategory = item.event;
                            }
                            /* li = that._renderItemData(ul, item);
                             if (item.event) {
                             li.attr("aria-label", item.event + " : " + item.label);
                             } */
                            $("<li></li>")
                                    .data("ui-autocomplete-item", item)
                                    .append('<a href="javascript:;"><input type="checkbox"/>' + item.label + '</a>')
                                    .appendTo(ul);
                        });
                    }
                });

                $("#trade").catcomplete({
                    delay: 0,
                    source: function (request, response) {
                        $.ajax({
                            type: "POST",
                            url: "tmp3.php",
                            data: {
                                trade: request.term,
                                trainingID: $('form[name=searchTraining] input[name=trainingID]').val(),
                                totalParticipants: $('form[name=searchTraining] input[name=totalParticipants]').val(),
                                male: $('form[name=searchTraining] input[name=male]').val(),
                                female: $('form[name=searchTraining] input[name=female]').val(),
                                district: $('form[name=searchTraining] input[name=district]').val(),
                                project: $('form[name=searchTraining] input[name=project]').val(),
                                fromDate: $('form[name=searchTraining] input[name=fromDate]').val(),
                                toDate: $('form[name=searchTraining] input[name=toDate]').val(),
                                rPerson: $('form[name=searchTraining] input[name=rPerson]').val()
                            },
                            success: response,
                            dataType: 'json',
                            minLength: 1
                        });
                    }
                });

            });
        </script>
    </head>
    <body>

        <form name="searchTraining">
            <div class="ui-widget">
                <label for="search">Search: </label>
                <textarea class="tradeF" name='trade' id='trade' placeholder="Trade" autocomplete="on" pattern="[a-zA-Z ]+" size="21" ></textarea>
            </div>

            <input pattern="[0-9]+" placeholder="Training ID" name="trainingID" size="1" class="idF" type="text" title="TrainingID">
            <input autocomplete="on" pattern="[0-9]+" placeholder="Total" name="totalParticipants" size="3" type="text" class="totalF">
            <input autocomplete="on" pattern="[0-9]+" placeholder="Male" name="male" size="3" type="text" class="maleF">
            <input autocomplete="on" pattern="[0-9]+" placeholder="Female" name="female" size="3" type="text" class="femaleF">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="District" name="district" size="3" type="text">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Project" name="project" size="3" type="text" value="kfw">
            From<input name="fromDate" size="3" type="text"><br />To<input name="toDate" size="3" type="text">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Venue" name="venue" size="3" type="text">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Resource Person" name="rPerson" size="3" type="text">
            <input type="hidden" name="defaulter" value="true" />
            <input type="hidden" name="questItem" value="" />
        </form>
    </body>
</html>

仅供参考:服务器响应是

[{event:'Commercial',label:'Adda Work'},
{event:'Commercial',label:'Alternative Dispute Resolution'},
{event:'Commercial',label:'Auto Electrician'},
{event:'Commercial',label:'Beautician'},
{event:'Staff',label:'Youth Activits Training'}]

我不知道我在哪里做错了但我已将其缩小到 $("#trade").catcomplete 代码块。

回答曲折的评论。 我们不需要 li 的 div 包装器。下面的代码将证明这一点。除了不使用远程数据源,基本相同。

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>jQuery UI Autocomplete - Categories</title>
        <link rel="stylesheet" href="../../res/jquery/jquery-ui/jquery-ui-1.12.1/jquery-ui.css">
        <style>
            .ui-autocomplete-category {
                font-weight: bold;
                padding: .2em .4em;
                margin: .8em 0 .2em;
                line-height: 1.5;
            }

            .ui-autocomplete {
                max-height: 600px;
                overflow-y: auto;
                /* prevent horizontal scrollbar */
                overflow-x: auto;
            }

            .ui-autocomplete-loading {
                background: white url("../img/ui-anim.gif") right center no-repeat;
            }
        </style>
        <script src="../../res/jquery/jquery1.x/jquery-1.12.4.js"></script>
        <script src="../../res/jquery/jquery-ui/jquery-ui-1.12.1/jquery-ui.js"></script>
        <script>
            $(function () {
                $.widget("custom.catcomplete", $.ui.autocomplete, {
                    _create: function () {
                        this._super();
                        this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
                    },
                    _renderMenu: function (ul, items) {
                        var that = this,
                                currentCategory = "";
                        $.each(items, function (index, item) {
                            var li;
                            if (item.event != currentCategory) {
                                ul.append("<li class='ui-autocomplete-category'>" + item.event + "</li>");
                                currentCategory = item.event;
                            }
                            $("<li></li>")
                                    .data("ui-autocomplete-item", item)
                                    .append('<a href="javascript:;"><input type="checkbox"/>' + item.label + '</a>')
                                    .appendTo(ul);
                        });
                    }
                });

                var data = [{event: 'Community', label: 'Agriculture Ex Worker (AEW)'},
                    {event: 'Community', label: 'BMT Trainings for CRPs'},
                    {event: 'Community', label: 'Carpentry'},
                    {event: 'Community', label: 'Fruits & Forest Nursery (Production & Marketting)'},
                    {event: 'Community', label: 'Heavy Machinery Excavator'},
                    {event: 'Community', label: 'Masonry'},
                    {event: 'Community', label: 'Mobile Repairing'},
                    {event: 'Community', label: 'Motor Cycle Repairing'},
                    {event: 'Community', label: 'Operation & Maintenance'},
                    {event: 'Community', label: 'Solar Panel Installation'},
                    {event: 'Community', label: 'Tailoring & Embroidery'},
                    {event: 'Staff', label: 'Engineers Training'},
                    {event: 'Staff', label: 'Engineers Training (Solar Panal)'},
                    {event: 'Staff', label: 'FATA Engineers Meeting'},
                    {event: 'Staff', label: 'FATA Projects Review Meeting'},
                    {event: 'Staff', label: 'Staff Orientation'}];

                $("#trade").catcomplete({
                 delay: 0,
                 source: data
                 });

            });
        </script>
    </head>
    <body>

        <form name="searchTraining">
            <div class="ui-widget">
                <label for="search">Search: </label>
                <textarea class="tradeF" name='trade' id='trade' placeholder="Trade" autocomplete="on" pattern="[a-zA-Z ]+" size="21" ></textarea>
            </div>

            <input pattern="[0-9]+" placeholder="Training ID" name="trainingID" size="1" class="idF" type="text" title="TrainingID">
            <input autocomplete="on" pattern="[0-9]+" placeholder="Total" name="totalParticipants" size="3" type="text" class="totalF">
            <input autocomplete="on" pattern="[0-9]+" placeholder="Male" name="male" size="3" type="text" class="maleF">
            <input autocomplete="on" pattern="[0-9]+" placeholder="Female" name="female" size="3" type="text" class="femaleF">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="District" name="district" size="3" type="text">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Project" name="project" size="3" type="text" value="kfw">
            From<input name="fromDate" size="3" type="text"><br />To<input name="toDate" size="3" type="text">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Venue" name="venue" size="3" type="text">
            <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Resource Person" name="rPerson" size="3" type="text">
            <input type="hidden" name="defaulter" value="true" />
            <input type="hidden" name="questItem" value="" />
        </form>
    </body>
</html>

上面的代码有效,即自动完成建议确实出现了。但这对我来说基本上没用,因为自动完成的来源是静态的,而我的要求是动态生成。

至于弹出的javascript代码是以后的问题(上面没有包含哪些代码)。

还是感谢 cmets。

【问题讨论】:

  • 自动完成需要存储在自动完成功能可以搜索到的本地数组中
  • 渲染你的项目时,我很确定你想在你的项目周围添加一个 &lt;div&gt; 包装器,在每个 &lt;li&gt; 内。
  • 另外,认为您会遇到一些问题,因为您的结果中有复选框。不确定哪个点击事件会冒泡,选择或复选框。
  • 我们不需要 li 的 div 包装器。下面的代码将证明这一点。除了不使用远程数据源,基本相同。

标签: jquery-ui autocomplete jquery-ui-autocomplete jquery-ui-widget-factory


【解决方案1】:

一些建议。由于您没有提供任何示例数据,因此很难测试或提供示例答案。

$(function() {
  $.widget("custom.catcomplete", $.ui.autocomplete, {
    _create: function() {
      this._super();
      this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
    },
    _renderMenu: function(ul, items) {
      var that = this,
        currentCategory = "";
      $.each(items, function(index, item) {
        var li;
        if (item.event != currentCategory) {
          ul.append("<li class='ui-autocomplete-category'>" + item.event + "</li>");
          currentCategory = item.event;
        }
        li = $("<li></li>")
          .data("ui-autocomplete-item", item)
          .append('<div><a href="javascript:;"><input type="checkbox"/>' + item.label + '</a></div>')
          .appendTo(ul);
      });
    }
  });

  $("#trade").catcomplete({
    delay: 0,
    source: function(request, response) {
      var myForm = $("form[name='searchTraining']");
      $.ajax({
        type: "POST",
        url: "tmp3.php",
        data: {
          trade: request.term,
          trainingID: $('[name=trainingID]', myForm).val(),
          totalParticipants: $('[name=totalParticipants]', myForm).val(),
          male: $('[name=male]', myForm).val(),
          female: $('[name=female]', myForm).val(),
          district: $('[name=district]', myForm).val(),
          project: $('[name=project]', myForm).val(),
          fromDate: $('[name=fromDate]', myForm).val(),
          toDate: $('[name=toDate]', myForm).val(),
          rPerson: $('[name=rPerson]', myForm).val()
        },
        success: response,
        dataType: 'json',
        minLength: 1
      });
    }
  });
});
.ui-autocomplete-category {
  font-weight: bold;
  padding: .2em .4em;
  margin: .8em 0 .2em;
  line-height: 1.5;
}

.ui-autocomplete {
  max-height: 100px;
  overflow-y: auto;
  /* prevent horizontal scrollbar */
  overflow-x: auto;
}

.ui-autocomplete-loading {
  background: white url("../img/ui-anim.gif") right center no-repeat;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form name="searchTraining">
  <div class="ui-widget">
    <label for="search">Search: </label>
    <textarea class="tradeF" name='trade' id='trade' placeholder="Trade" autocomplete="on" pattern="[a-zA-Z ]+" size="21"></textarea>
  </div>
  <input pattern="[0-9]+" placeholder="Training ID" name="trainingID" size="1" class="idF" type="text" title="TrainingID">
  <input autocomplete="on" pattern="[0-9]+" placeholder="Total" name="totalParticipants" size="3" type="text" class="totalF">
  <input autocomplete="on" pattern="[0-9]+" placeholder="Male" name="male" size="3" type="text" class="maleF">
  <input autocomplete="on" pattern="[0-9]+" placeholder="Female" name="female" size="3" type="text" class="femaleF">
  <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="District" name="district" size="3" type="text">
  <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Project" name="project" size="3" type="text" value="kfw"> From
  <input name="fromDate" size="3" type="text"><br />To<input name="toDate" size="3" type="text">
  <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Venue" name="venue" size="3" type="text">
  <input autocomplete="on" pattern="[a-zA-Z ]+" placeholder="Resource Person" name="rPerson" size="3" type="text">
  <input type="hidden" name="defaulter" value="true" />
  <input type="hidden" name="questItem" value="" />
</form>

【讨论】:

  • 先生,首先感谢您的回答。是否提供了您提供的代码;运行,因为当我在 textarea 中输入字符时它会出错。就样本数据而言,任何字符都可以执行,例如在 textarea 中键入“a”。它不关心键入的内容;只要它会在textarea中提出一些建议。服务器端应该只需要回显一个 json 数组,例如
  • OK 你的代码是正确的,除了最后一个 rPerson 你错过了一个方括号并且 myForm 应该是 searchTraining。但尽管如此,我已经用你的代码替换了我的代码,它也没有给出建议或自动完成。
  • @Adeel 你在控制台看到了什么?您在“网络”部分看到什么响应?
  • 如果我输入 Mo;在控制台下我注意到了。即没有错误,而在网络部分我得到了这个; [{event:'社区',label:'手机维修'}, {event:'社区',label:'摩托车维修'}]
  • 好的。所以ajax正在运行并返回结果。会考虑在你的 each 中添加一些 console.log() 部分。
【解决方案2】:

问题在于我怀疑 JavaScript 的编码是次要的和神秘的。当我在 php 中创建 Json 数组时,我使用了引号而不是双引号。即

"{'event':'Community','label':'Agriculture'}" 

我应该使用

'{"event":"Community","label":"Agriculture"}' 

当我用双引号反转引号时,它就像一个魅力。 顺便说一句:@twisty 感谢您一路上帮助我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2012-03-12
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多