首页 文章

twitter bootstrap typeahead ajax示例

提问于
浏览
268

我正在尝试找到一个twitter bootstrap typeahead元素的工作示例,该元素将进行ajax调用以填充它的下拉列表 .

我有一个现有的工作jquery自动完成示例,它定义了ajax url以及如何处理回复

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { minChars:3, max:20 };
    $("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

我需要更改什么来将其转换为typeahead示例?

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { source:'/index/runnerfilter/format/html', items:5 };
    $("#runnerquery").typeahead(options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

我'm going to wait for the ' Add remote sources support for typeahead'问题有待解决 .

16 回答

  • 292

    编辑:在bootstrap 3中不再捆绑typeahead . 退房:

    从Bootstrap 2.1.0到2.3.2,你可以这样做:

    $('.typeahead').typeahead({
        source: function (query, process) {
            return $.get('/typeahead', { query: query }, function (data) {
                return process(data.options);
            });
        }
    });
    

    要使用这样的JSON数据:

    {
        "options": [
            "Option 1",
            "Option 2",
            "Option 3",
            "Option 4",
            "Option 5"
        ]
    }
    

    请注意,JSON数据必须是正确的mime类型(application / json),因此jQuery将其识别为JSON .

  • 2

    您可以使用支持ajax调用的BS Typeahead fork . 然后你就可以写:

    $('.typeahead').typeahead({
        source: function (typeahead, query) {
            return $.get('/typeahead', { query: query }, function (data) {
                return typeahead.process(data);
            });
        }
    });
    
  • 1

    从Bootstrap 2.1.0开始:

    HTML:

    <input type='text' class='ajax-typeahead' data-link='your-json-link' />
    

    使用Javascript:

    $('.ajax-typeahead').typeahead({
        source: function(query, process) {
            return $.ajax({
                url: $(this)[0].$element[0].dataset.link,
                type: 'get',
                data: {query: query},
                dataType: 'json',
                success: function(json) {
                    return typeof json.options == 'undefined' ? false : process(json.options);
                }
            });
        }
    });
    

    现在,您可以制作统一的代码,在您的HTML代码中放置“json-request”链接 .

  • 0

    所有响应都引用BootStrap 2 typeahead,它在BootStrap 3中不再存在 .

    对于在这里寻找使用新post-Bootstrap Twitter typeahead.js的AJAX示例的其他人,这是一个工作示例 . 语法有点不同:

    $('#mytextquery').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      limit: 12,
      async: true,
      source: function (query, processSync, processAsync) {
        processSync(['This suggestion appears immediately', 'This one too']);
        return $.ajax({
          url: "/ajax/myfilter.php", 
          type: 'GET',
          data: {query: query},
          dataType: 'json',
          success: function (json) {
            // in this example, json is simply an array of strings
            return processAsync(json);
          }
        });
      }
    });
    

    此示例使用同步(对 processSync 的调用)和异步建议,因此您会看到一些选项立即出现,然后添加其他选项 . 你可以使用其中一个 .

    有许多可绑定事件和一些非常强大的选项,包括使用对象而不是字符串,在这种情况下,您将使用自己的自定义 display 函数将项目呈现为文本 .

  • 42

    我用ajax功能扩充了原始的typeahead Bootstrap插件 . 非常好用:

    $("#ajax-typeahead").typeahead({
         ajax: "/path/to/source"
    });
    

    这是github回购:Ajax-Typeahead

  • 69

    我对jquery-ui.min.js做了一些修改:

    //Line 319 ORIG:
    this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
    // NEW:
    this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...
    
    // Line 328 ORIG:
    this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
    // NEW:this.element.attr....
    
    // Line 329 ORIG:
    this.active=a.eq(0).children("a")
    this.active.children("a")
    // NEW:
    this.active=a.eq(0).addClass("active").children("a")
    this.active.removeClass("active").children("a")`
    

    并添加以下css

    .dropdown-menu {
        max-width: 920px;
    }
    .ui-menu-item {
        cursor: pointer;        
    }
    

    工作完美 .

  • 1

    我正在使用这种方法

    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
        {
        name: 'options',
        displayKey: 'value',
        source: function (query, process) {
            return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
                var matches = [];
                $.each(data, function(i, str) {
                    matches.push({ value: str });
                });
                return process(matches);
    
            },'json');
        }
    });
    
  • 24

    可以使用Bootstrap进行调用 . 当前版本没有任何源更新问题Trouble updating Bootstrap's typeahead data-source with post response,即更新后的引导程序源可以再次修改 .

    请参考下面的示例:

    jQuery('#help').typeahead({
        source : function(query, process) {
            jQuery.ajax({
                url : "urltobefetched",
                type : 'GET',
                data : {
                    "query" : query
                },
                dataType : 'json',
                success : function(json) {
                    process(json);
                }
            });
        },
        minLength : 1,
    });
    
  • 5

    对于那些寻找已接受答案的咖啡版版本的人:

    $(".typeahead").typeahead source: (query, process) ->
      $.get "/typeahead",
        query: query
      , (data) ->
        process data.options
    
  • 116

    我经历了这篇文章,一切都不想正常工作,最终从几个答案拼凑出来,所以我有一个100%的工作演示,并将它粘贴在这里作为参考 - 粘贴到一个PHP文件,并确保包括在正确的地方 .

    <?php if (isset($_GET['typeahead'])){
        die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
    }
    ?>
    <link href="bootstrap.css" rel="stylesheet">
    <input type="text" class='typeahead'>
    <script src="jquery-1.10.2.js"></script>
    <script src="bootstrap.min.js"></script>
    <script>
    $('.typeahead').typeahead({
        source: function (query, process) {
            return $.get('index.php?typeahead', { query: query }, function (data) {
                return process(JSON.parse(data).options);
            });
        }
    });
    </script>
    
  • 3

    更新:我使用this fork修改了我的代码

    我也没有使用$ .each,而是根据Tomislav Markovski的建议更改为$ .map

    $('#manufacturer').typeahead({
        source: function(typeahead, query){
            $.ajax({
                url: window.location.origin+"/bows/get_manufacturers.json",
                type: "POST",
                data: "",
                dataType: "JSON",
                async: false,
                success: function(results){
                    var manufacturers = new Array;
                    $.map(results.data.manufacturers, function(data, item){
                        var group;
                        group = {
                            manufacturer_id: data.Manufacturer.id,
                            manufacturer: data.Manufacturer.manufacturer
                        };
                        manufacturers.push(group);
                    });
                    typeahead.process(manufacturers);
                }
            });
        },
        property: 'name',
        items:11,
        onselect: function (obj) {
    
        }
    });
    

    但是我遇到了一些问题

    未捕获的TypeError:无法调用未定义的方法'toLowerCase'

    正如你在新帖子上看到的那样我试图找出here

    希望这个更新对你有任何帮助......

  • 0

    如果您的服务未返回正确的application / json内容类型标头,请尝试此操作:

    $('.typeahead').typeahead({
        source: function (query, process) {
            return $.get('/typeahead', { query: query }, function (data) {
                var json = JSON.parse(data); // string to json
                return process(json.options);
            });
        }
    });
    
  • 2

    我没有适合您的工作示例,也没有一个非常干净的解决方案,但让我告诉您我发现了什么 .

    如果你查看TypeAhead的javascript代码,它看起来像这样:

    items = $.grep(this.source, function (item) {
        if (that.matcher(item)) return item
      })
    

    此代码使用jQuery“grep”方法匹配源数组中的元素 . 我没有看到任何可以挂在AJAX调用中的地方,因此没有一个“干净”的解决方案 .

    但是,你可以这样做的一种有点hacky方式是利用grep方法在jQuery中的工作方式 . grep的第一个参数是源数组,第二个参数是用于匹配源数组的函数(通知Bootstrap调用初始化时提供的“匹配器”) . 你可以做的是将源设置为一个虚拟的单元素数组,并将匹配器定义为一个带有AJAX调用的函数 . 这样,它只运行一次AJAX调用(因为你的源数组只有一个元素) .

    这个解决方案不仅是hacky,而且还会遇到性能问题,因为TypeAhead代码旨在对每个按键进行查找(AJAX调用应该只发生在每几次击键或一定量的空闲时间之后) . 我的建议是尝试一下,但要坚持使用不同的自动完成库,或者只在遇到任何问题时才将其用于非AJAX情况 .

  • -1

    使用ajax时,如果您无法正确显示结果,请尝试 $.getJSON() 而不是 $.get() .

    在我的情况下,当我使用 $.get() 时,我只得到每个结果的第一个字符,尽管我使用 json_encode() 服务器端 .

  • 2

    我使用 $().one() 来解决这个问题;当页面加载时,我将ajax发送到服务器并等待完成 . 然后将结果传递给函数 . $().one() 很重要 . 因为强制 typehead.js 连接到输入一次 . 抱歉写不好 .

    (($) => {
        
        var substringMatcher = function(strs) {
            return function findMatches(q, cb) {
              var matches, substringRegex;
              // an array that will be populated with substring matches
              matches = [];
          
              // regex used to determine if a string contains the substring `q`
              substrRegex = new RegExp(q, 'i');
          
              // iterate through the pool of strings and for any string that
              // contains the substring `q`, add it to the `matches` array
              $.each(strs, function(i, str) {
                if (substrRegex.test(str)) {
                  matches.push(str);
                }
              });
              cb(matches);
            };
          };
          
          var states = [];
          $.ajax({
              url: 'https://baconipsum.com/api/?type=meat-and-filler',
              type: 'get'
          }).done(function(data) {
            $('.typeahead').one().typeahead({
                hint: true,
                highlight: true,
                minLength: 1
              },
              {
                name: 'states',
                source: substringMatcher(data)
              });
          })
          
    
    })(jQuery);
    
    .tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */
    .tt-hint {
        width: 396px;
        height: 30px;
        padding: 8px 12px;
        font-size: 24px;
        line-height: 30px;
        border: 2px solid #ccc;
        border-radius: 8px;
        outline: none;
    }
    
    .tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    }
    
    .tt-hint {
        color: #999;
    }
    
    .tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */
        width: 422px;
        margin-top: 12px;
        padding: 8px 0;
        background-color: #fff;
        border: 1px solid #ccc;
        border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 8px;
        box-shadow: 0 5px 10px rgba(0,0,0,.2);
    }
    
    .tt-suggestion {
        padding: 3px 20px;
        font-size: 18px;
        line-height: 24px;
        cursor: pointer;
    }
    
    .tt-suggestion:hover {
        color: #f0f0f0;
        background-color: #0097cf;
    }
    
    .tt-suggestion p {
        margin: 0;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
    
    <input class="typeahead" type="text" placeholder="where ?">
    
  • 0
    $('#runnerquery').typeahead({
            source: function (query, result) {
                $.ajax({
                    url: "db.php",
                    data: 'query=' + query,            
                    dataType: "json",
                    type: "POST",
                    success: function (data) {
                        result($.map(data, function (item) {
                            return item;
                        }));
                    }
                });
            },
            updater: function (item) {
            //selectedState = map[item].stateCode;
    
           // Here u can obtain the selected suggestion from the list
    
    
            alert(item);
                }
    
        }); 
    
     //Db.php file
    <?php       
    $keyword = strval($_POST['query']);
    $search_param = "{$keyword}%";
    $conn =new mysqli('localhost', 'root', '' , 'TableName');
    
    $sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
    $sql->bind_param("s",$search_param);            
    $sql->execute();
    $result = $sql->get_result();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
        $Resut[] = $row["name"];
        }
        echo json_encode($Result);
    }
    $conn->close();
    

    ?>

相关问题