twitter Bootstrap typehead ajax przykład

Próbuję znaleźć działający przykład elementu twitter bootstrap typeahead , który wywoła wywołanie ajax, aby wypełnić to rozwijane.

Mam działający przykład autouzupełniania jquery, który definiuje adres URL ajax i jak przetworzyć odpowiedź

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

Co muszę zmienić, aby przekonwertować to na przykład typehead?

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

Poczekam aż problem "Add remote sources support for typeahead " zostanie rozwiązany.

Author: user, 2012-02-10

16 answers

Edit: typeahead nie jest już dołączany do Bootstrap 3. Sprawdź:

Od wersji Bootstrap 2.1.0 do 2.3.2 możesz to zrobić:

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

Aby wykorzystać dane JSON w ten sposób:

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

Zauważ, że dane JSON muszą być odpowiedniego typu mime (application/json), więc jQuery rozpoznaje je jako JSON.

 290
Author: Stijn Van Bael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:15

Możesz użyć BS typehead fork który obsługuje połączenia ajax. Wtedy będziesz mógł napisać:

$('.typeahead').typeahead({
    source: function (typeahead, query) {
        return $.get('/typeahead', { query: query }, function (data) {
            return typeahead.process(data);
        });
    }
});
 116
Author: bogert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-07 14:56:23

Począwszy od 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);
            }
        });
    }
});

Teraz możesz utworzyć zunifikowany kod, umieszczając linki" JSON-request " w kodzie HTML.

 69
Author: Thantifaxath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-31 11:32:20

Wszystkie odpowiedzi odnoszą się do typu BootStrap 2, który nie występuje już w BootStrap 3.

Dla każdego, kto szuka tutaj przykładu AJAX ' a z użyciem nowego post-Bootstrap typu Twitter.js , Oto działający przykład. Składnia jest trochę inna:

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

Ten przykład wykorzystuje zarówno synchroniczne (wywołanie processSync), jak i asynchroniczne sugestie, więc niektóre opcje pojawiają się natychmiast, a inne są dodawane. Możesz po prostu użyć jedno albo drugie.

Istnieje wiele bindowalnych zdarzeń i kilka bardzo zaawansowanych opcji, w tym praca z obiektami, a nie ciągami znaków, w którym to przypadku możesz użyć własnej niestandardowej funkcji display do renderowania elementów jako tekstu.

 42
Author: Jonathan Lidbeck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-20 04:49:15

Rozszerzyłem oryginalną wtyczkę typehead Bootstrap o możliwości ajax. Bardzo łatwy w użyciu:

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

Oto repo github: Ajax-Typehead

 24
Author: Paul Warelis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-31 14:46:26

Zrobiłem kilka modyfikacji w 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")`

I dodać następujący css

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}
Działa idealnie.
 5
Author: bmoers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-13 06:46:02

Można wykonywać połączenia za pomocą Bootstrap. Aktualna wersja nie ma żadnych problemów z aktualizacją źródła Problem z aktualizacją źródła danych typu Bootstrap z odpowiedzią post , tzn. źródło Bootstrapa po zaktualizowaniu można ponownie zmodyfikować.

Proszę zapoznać się z poniższym przykładem:

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,
});
 2
Author: neoeahit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:30

Do tych, którzy szukają kawowej wersji zaakceptowanej odpowiedzi:

$(".typeahead").typeahead source: (query, process) ->
  $.get "/typeahead",
    query: query
  , (data) ->
    process data.options
 2
Author: Hendrik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-24 23:24:13

Przejrzałem ten post i wszystko nie chciało działać poprawnie i ostatecznie poskładałem fragmenty z kilku odpowiedzi, więc mam 100% działające demo i wkleję je tutaj w celach informacyjnych-wklej to do pliku php i upewnij się, że Zawiera są we właściwym miejscu.

<?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>
 2
Author: l0ft13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-04 21:56:10

Używam tej metody

$('.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');
    }
});
 2
Author: Krava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-22 19:14:19

UPDATE: zmodyfikowałem mój kod używając tego fork

Również zamiast używać $.każdy zmieniłem na $.Mapa według sugestii Tomislava Markovskiego

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

    }
});

Jednak napotykam pewne problemy przez uzyskanie

Uncaught TypeError: Cannot called method 'toLowerCase' of undefined

Jak widać na nowszym poście staram się dowiedzieć tutaj

Mam nadzieję, że ta aktualizacja będzie dla ciebie pomocna...

 1
Author: mmoscosa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:30

Spróbuj tego, jeśli twój serwis nie zwraca odpowiedniego nagłówka typu 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);
        });
    }
});
 1
Author: Andres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-16 22:43:03

Nie mam dla Ciebie przykładu ani bardzo czystego rozwiązania, ale powiem ci, co znalazłem.

Jeśli spojrzysz na kod javascript dla Typehead wygląda to tak:

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

Ten kod używa metody jQuery "grep" do dopasowania elementu w tablicy źródłowej. Nie widziałem żadnych miejsc, które można podłączyć do połączenia AJAX, więc nie ma na to "czystego" rozwiązania.

Jednak jednym z nieco chwiejnych sposobów, które możesz zrobić, jest wykorzystanie sposobu, w jaki metoda grep działa w jQuery. Pierwszym argumentem grepa jest tablica źródłowa, a drugim jest funkcja, która jest używana do dopasowania tablicy źródłowej (zauważ, że Bootstrap wywołuje "matcher" podany podczas inicjalizacji). Co można zrobić, to ustawić źródło do atrapy tablicy jednoelementowej i zdefiniować matcher jako funkcję z wywołaniem AJAX w nim. W ten sposób wywołanie AJAX zostanie uruchomione tylko raz (ponieważ Twoja tablica źródłowa ma tylko jeden element).

To rozwiązanie jest nie tylko hacky, ale będzie cierpiał z powodu problemów z wydajnością, ponieważ Kod Typehead jest przeznaczony do wyszukiwania przy każdym naciśnięciu klawisza (połączenia AJAX powinny mieć miejsce tylko przy każdym naciśnięciu klawisza lub po pewnym czasie bezczynności). Radzę spróbować, ale trzymaj się innej biblioteki autouzupełniania lub używaj jej tylko w sytuacjach innych niż AJAX, jeśli napotkasz jakiekolwiek problemy.

 0
Author: Aamer Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-13 17:17:29

Podczas korzystania z ajax, spróbuj $.getJSON() zamiast $.get(), Jeśli masz problemy z prawidłowym wyświetlaniem wyników.

W moim przypadku otrzymałem tylko pierwszy znak każdego wyniku, gdy użyłem $.get(), chociaż użyłem json_encode() Po stronie serwera.

 0
Author: larsbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-16 07:42:38

Używam $().one() do rozwiązania tego; Po załadowaniu strony wysyłam ajax na serwer i czekam na gotowe. Następnie przekaż wynik do funkcji.$().one() jest ważne .Ponieważ siła typehead.js aby dołączyć do wejścia jeden raz. przepraszam za złe pisanie.

(($) => {
    
    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
Author: ali karimi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-05 14:03:49
 $('#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();

?>

 -1
Author: Mohamed Ayed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 06:55:47