Twitter Bootstrap Typeahead Ajax 示例

285

我正在尝试查找可工作的Twitter Bootstrap补全示例,该示例将进行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];
                }
            );
       ..

我要等待 'Add remote sources support for typeahead' 这个问题得到解决。


更具体地说,我想知道自动完成选项和结果处理函数如何映射到textahead选项?是否有一组定义的textalert结果处理函数可以被覆盖,或者这些方法名称是从底层的jquery api继承而来的? - emeraldjava
1
请问您现在可以将Stijn Van Bael的回答标记为正确答案吗?bogert的答案只适用于过时版本的Bootstrap。 - Giles Roberts
17个回答

1

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

此外,根据Tomislav Markovski的建议,我改用了$.map而不是$.each

$('#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) {

    }
});

然而,我在获取时遇到了一些问题

未捕获的类型错误:无法调用未定义的“toLowerCase”方法

正如您在新帖子中看到的那样,我正在尝试弄清楚这里的问题。

希望这个更新对您有所帮助...


与 OP 无关:我会使用 Array.map 替代 $.each,并将整个 success 回调函数的内容替换为 var manufacturers = results.data.manufacturers.map(function (item) { return { id: item.Manufacturer.id, manufacturer: item.Manufacturer.manufacturer } }); - Tomislav Markovski
谢谢@TomislavMarkovski,我按照您的建议修改了我的代码。 - mmoscosa
请使用最新版本中的“display”代替“property”。 - Dhara

1

我看了这篇文章,但并没有按照要求正常工作。最终我从几个答案中拼凑出了正确的代码,并在此提供一个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>

1

我使用$().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 ?">


1

如果需要 CoffeeScript 版本的已接受答案,请参考以下内容:

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

1

现在您只需使用预取:

const bloodhound = new Bloodhound({
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '/jsonarrayendpoint',
    datumTokenizer: Bloodhound.tokenizers.whitespace
});

$('#search').typeahead({
    highlight: true
},
{
    source: bloodhound
});

如果你的结果只是一个字符串数组,那么上面的内容就足够了。但是如果它们是对象,你还需要做更多的工作。假设数据具有Id(.id)和要显示的文本(.name),那么请继续阅读。
const bloodhound = new Bloodhound({
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '/jsonresultsendpoint',

    identify: d => d.id,
    datumTokenizer: d => Bloodhound.tokenizers.whitespace(d.name)
});

$('#search').typeahead({
    highlight: true
},
{
    source: bloodhound,
    display: 'name',
});

-1
当使用ajax时,如果在结果的正确显示上遇到问题,请尝试使用$.getJSON()而不是$.get()
在我的情况下,当我使用$.get()时,只能得到每个结果的第一个字符,尽管我在服务器端使用了json_encode()

-2
 $('#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();

?>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接