簡體   English   中英

twitter bootstrap typeahead ajax示例

[英]twitter bootstrap typeahead ajax example

我正在嘗試查找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];
                }
            );
       ..

我需要進行什么更改才能將其轉換為預輸入示例?

<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];
                }
            );
       ..

我將等待解決“ 為預輸入添加遠程源支持 ”問題得到解決。

編輯:typeahead不再捆綁在Bootstrap 3中。簽出:

從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。

您可以使用支持ajax調用的BS Typeahead分支 然后,您將能夠編寫:

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

從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”鏈接。

所有響應都涉及到BootStrap 2提前輸入,BootStrap 3中不再存在。

對於其他在這里使用新的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的調用)和異步建議,因此您會看到一些選項立即出現,然后添加了其他選項。 您可以只使用其中一個。

有很多可綁定的事件和一些非常強大的選項,包括使用對象而不是字符串,在這種情況下,您將使用自己的自定義顯示功能將項目呈現為文本。

我使用ajax功能增強了原始的typeahead Bootstrap插件。 非常容易使用:

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

這是github倉庫: Ajax-Typeahead

我對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;        
}

完美的作品。

我正在使用這種方法

$('.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');
    }
});

可以使用Bootstrap撥打電話。 當前版本沒有任何源代碼更新問題麻煩地更新具有引導響應的Bootstrap的typeahead數據源 ,即一旦更新的引導程序源可以再次修改。

請參考以下示例:

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,
});

對於那些尋找接受答案的咖啡腳本版本的人:

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

我經歷了這篇文章,一切都不想正常工作,最終將幾個答案拼湊在一起,所以我有一個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>

更新:我使用 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”

正如您在較新的帖子中看到的那樣,我試圖在這里

希望此更新對您有幫助...

如果您的服務沒有返回正確的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);
        });
    }
});

使用ajax時,如果無法正確顯示結果,請嘗試使用$.getJSON()而不是$.get()

就我而言,盡管我使用json_encode()服務器端,但我只使用$.get()時得到每個結果的第一個字符。

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

我沒有適合您的示例,也沒有一個非常干凈的解決方案,但是讓我告訴您所找到的內容。

如果您查看TypeAhead的javascript代碼,則如下所示:

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

此代碼使用jQuery“ grep”方法來匹配源數組中的元素。 我沒有看到可以掛接到AJAX調用的任何位置,因此沒有“干凈”的解決方案。

但是,一種可行的方法是利用grep方法在jQuery中的工作方式。 grep的第一個參數是源數組,第二個參數是用於匹配源數組的函數(注意,Bootstrap會在初始化時調用您提供的“ matcher”)。 您可以做的是將源設置為虛擬的一元數組,然后將匹配器定義為帶有AJAX調用的函數。 這樣,它將只運行一次AJAX調用(因為源數組中只有一個元素)。

該解決方案不僅笨拙,而且還會遇到性能問題,因為TypeAhead代碼旨在在每次按鍵時進行查找(AJAX調用實際上應該僅在每幾次擊鍵或一定時間的空閑時間之后才發生)。 我的建議是嘗試一下,但是請堅持使用其他自動完成庫,或者在遇到任何問題時僅將其用於非AJAX情況。

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

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM