2016-09-08 4 views
0

Я пытаюсь создать поле поиска автозаполнения из json-файла с помощью JQuery Typeahead, чтобы иметь предварительный просмотр автозаполнения на входах поиска, похожих на поиск Google, на основе этого примера: http://www.runningcoder.org/jquerytypeahead/demo/ (Beer v1).JQuery Typeahead

HTML

<form> 
    <div class="typeahead__container"> 
     <div class="typeahead__field"> 
     <span class="typeahead__query"> 
      <input class="js-typeahead-input" 
        name="q" 
        type="search" 
        autofocus 
        autocomplete="off"> 
     </span> 
     </div> 
    </div> 
</form> 

JAVASCRIPT

var data = { 
    countries: ["Afghanistan", "Albania", "Algeria"], 
    capitals: ["Abu Dhabi", "Abuja", "Accra"] 
}; 
typeof $.typeahead === 'function' && $.typeahead({ 
    input: ".js-typeahead-input", 
    minLength: 1, 
    order: "asc", 
    group: true, 
    maxItemPerGroup: 5, 
    groupOrder: function() { 
     var scope = this, 
      sortGroup = []; 
     for (var i in this.result) { 
      sortGroup.push({ 
       group: i, 
       length: this.result[i].length 
      }); 
     } 
     sortGroup.sort(
      scope.helper.sort(
       ["length"], 
       true, // false = desc, the most results on top 
       function (a) { 
        return a.toString().toUpperCase() 
       } 
      ) 
     ); 
     return $.map(sortGroup, function (val, i) { 
      return val.group 
     }); 
    }, 
    hint: true, 
    dropdownFilter: "All", 
    template: "{{display}}, <small><em>{{group}}</em></small>", 
    emptyTemplate: "nothing for : {{query}}", 
    source: { 
     country: { 
      data: data.countries 
     }, 
     capital: { 
      data: data.capitals 
     } 
    }, 
    debug: true 
}); 

Я пытался заменить фактический источник,

    source: { 
        "coutries": { 
            ajax: { 
                url: "coutries.json", 
                path: "data" 
            } 
        }, 
        "capitals": { 
            ajax: { 
                url: "capitals.json", 
                path: "data" 
            } 
        }, 
} 

Проблема в том, что я не могу добавлять файлы в формате JSON загрузить результаты из.

Окончательный результат должен выглядеть следующим образом: enter image description here

+0

Пожалуйста, объясните, что не работает: дайте нам сообщение об ошибке, или результат у вас есть! – rebe100x

+0

Проблема в том, что я не могу добавить файлы json для загрузки результатов из него. – Clementine

ответ

0

Вы можете использовать Ajax - GET метод для получения данных из базы данных или из других вы хотите. См следующий сценарий:

$(document).ready(function(){ 
    $.ajax({ 
     type: "GET", 
     url: "your ajax url", 
     dataType: "json", 
     success: function(data) { 
      typeof $.typeahead === 'function' && $.typeahead({ 
       input: ".js-typeahead-input", 
       minLength: 1, //minimum character length 
       order: "asc", 
       hint: true, 
       source: data, 
       debug: true 
      }); 
     } 
}); 
Смежные вопросы