如何根据从 ajax 调用返回的数据动态地将选项添加到我的自动完成功能?

Posted

技术标签:

【中文标题】如何根据从 ajax 调用返回的数据动态地将选项添加到我的自动完成功能?【英文标题】:How do I dynamically add options to my autocomplete based on data returned from an ajax call? 【发布时间】:2020-02-08 00:52:09 【问题描述】:

我正在尝试实现在 jquery ui 网站上看到的自动完成组合框;但是,在他们的示例中,他们的 html 中有硬编码选项。我想运行一个从数据库返回值的 ajax 调用,然后用这些值填充组合框。有谁知道我如何最好地解决这个问题?

请看下面来自 jquery-ui 的示例代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Combobox</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .custom-combobox 
    position: relative;
    display: inline-block;
  
  .custom-combobox-toggle 
    position: absolute;
    top: 0;
    bottom: 0;
    margin-left: -1px;
    padding: 0;
  
  .custom-combobox-input 
    margin: 0;
    padding: 5px 10px;
  
  </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.combobox", 
      _create: function() 
        this.wrapper = $( "<span>" )
          .addClass( "custom-combobox" )
          .insertAfter( this.element );

        this.element.hide();
        this._createAutocomplete();
        this._createShowAllButton();
      ,

      _createAutocomplete: function() 
        var selected = this.element.children( ":selected" ),
          value = selected.val() ? selected.text() : "";

        this.input = $( "<input>" )
          .appendTo( this.wrapper )
          .val( value )
          .attr( "title", "" )
          .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
          .autocomplete(
            delay: 0,
            minLength: 0,
            source: $.proxy( this, "_source" )
          )
          .tooltip(
            classes: 
              "ui-tooltip": "ui-state-highlight"
            
          );

        this._on( this.input, 
          autocompleteselect: function( event, ui ) 
            ui.item.option.selected = true;
            this._trigger( "select", event, 
              item: ui.item.option
            );
          ,

          autocompletechange: "_removeIfInvalid"
        );
      ,

      _createShowAllButton: function() 
        var input = this.input,
          wasOpen = false;

        $( "<a>" )
          .attr( "tabIndex", -1 )
          .attr( "title", "Show All Items" )
          .tooltip()
          .appendTo( this.wrapper )
          .button(
            icons: 
              primary: "ui-icon-triangle-1-s"
            ,
            text: false
          )
          .removeClass( "ui-corner-all" )
          .addClass( "custom-combobox-toggle ui-corner-right" )
          .on( "mousedown", function() 
            wasOpen = input.autocomplete( "widget" ).is( ":visible" );
          )
          .on( "click", function() 
            input.trigger( "focus" );

            // Close if already visible
            if ( wasOpen ) 
              return;
            

            // Pass empty string as value to search for, displaying all results
            input.autocomplete( "search", "" );
          );
      ,

      _source: function( request, response ) 
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
        response( this.element.children( "option" ).map(function() 
          var text = $( this ).text();
          if ( this.value && ( !request.term || matcher.test(text) ) )
            return 
              label: text,
              value: text,
              option: this
            ;
        ) );
      ,

      _removeIfInvalid: function( event, ui ) 

        // Selected an item, nothing to do
        if ( ui.item ) 
          return;
        

        // Search for a match (case-insensitive)
        var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
        this.element.children( "option" ).each(function() 
          if ( $( this ).text().toLowerCase() === valueLowerCase ) 
            this.selected = valid = true;
            return false;
          
        );

        // Found a match, nothing to do
        if ( valid ) 
          return;
        

        // Remove invalid value
        this.input
          .val( "" )
          .attr( "title", value + " didn't match any item" )
          .tooltip( "open" );
        this.element.val( "" );
        this._delay(function() 
          this.input.tooltip( "close" ).attr( "title", "" );
        , 2500 );
        this.input.autocomplete( "instance" ).term = "";
      ,

      _destroy: function() 
        this.wrapper.remove();
        this.element.show();
      
    );

    $( "#combobox" ).combobox();
    $( "#toggle" ).on( "click", function() 
      $( "#combobox" ).toggle();
    );
   );
  </script>
</head>
<body>

<div class="ui-widget">
  <label>Your preferred programming language: </label>
  <select id="combobox">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="javascript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="php">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
  </select>
</div>
<button id="toggle">Show underlying select</button>


</body>
</html>

【问题讨论】:

初始化组合框时可以使用source选项。 【参考方案1】:
- Remove the existing hardcoded <select id="combobox"> dropdown and add DIV continer <div id="combobox-data"></div>  
- Remove  the $( "#combobox" ).combobox();  
- For the above example, Create a dropdown-values.cfm page with the below code Query
        <select id="combobox">
            <option value="">Select one...</option>
            <cfoutput query="query">
                <option value="Query.id">Query.name</option>
            </cfoutput>
        </select>
- Create a function and call the dropdown-values.cfm page using ajax 
    function dynamicDropDownValues() 
        $.ajax(
            type: "POST",
            url: "dropdown-values.cfm",
            success: function(data)
                    
                        $('#combobox-data').append(data);
                        $( "#combobox" ).combobox();
                    ,
            failure: function () 
                alert("Failed!");
            
        );
    
- The dynamicDropDownValues() call should be in DOM load ( $( function()  dynamicDropDownValues()  )

【讨论】:

这似乎没有返回任何东西

以上是关于如何根据从 ajax 调用返回的数据动态地将选项添加到我的自动完成功能?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ASP.NET Core MVC 中添加分页,在 AJAX 调用中动态创建的表上

AJAX如何动态地将行添加到表中

谁知道怎么用ajax实现选择下拉框的时候动态从数据库读取数据吗

基于ajax调用的动态href url

从动态加载的页面调用的 AJAX 返回异步结果

Django - 如何正确地将列表从模板发送到 AJAX 以查看?