2014-02-10 2 views
2

처음으로 twitter typeahead.js를 사용하고 있습니다. 먼저 간단한 로컬 배열로 시작했고 작동하도록했습니다.Typeahead bloodhound가 작동하지 않음

다음 단계로 .json 파일과 함께 작동 시키려고합니다. 몇 가지 옵션을 시도했지만 작동하도록 만들 수는 없으며 그 중 일부는 피 헤드가 어떻게 작동하는지 잘 이해하지 못하기 때문에 나타납니다.

HTML 코드

<div class="search_content"> 
    <input class="products" type="text" placeholder="products" value=""> 
</div> 

JSON 파일 (의 일부)는

{ 
    "Products": [ 
     { "name": "Pink Floyd", 
      "Album": "The Best Of Pink Floyd: A Foot In The Door", 
      "Label": "EMI UK", 
      "Tracks":"Hey You, See Emily Play, The Happiest Days Of Our Lives, Another Brick in The Wall (Part 2), Have a cigar, Wish You Where Here, Time, The Great Gig in the Sky, Money, Comfortably Numb, High Hopes, Learning to Fly, The Fletcher Memorial Home, Shine On You Crazy Diamond, Brain Damage, Eclipse" , 
      "Price": "16.40", 
      "Genre": "Rock" 

     }, 
     { 
      "name": "Depeche Mode", 
      "Album": "A Question Of Time", 
      "Label": "Mute", 
      "Tracks":"A Question Of Time, Black Celebration, Something To Do, Stripped, More Than A Party, A Question Of Time(extended), Black Celebration" , 
      "Price": "4.68" , 
      "Genre": "Rock" 
     } 

    ] 
} 

Typeahead.js 코드

그것은 다음과 같습니다
var products = new Bloodhound({ 
    datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name); }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    prefetch: '/js/products.json' 

}); 

products.initialize(); 

$('.products').typeahead(null, { 
    name: 'products', 
    displayKey: 'name', 
    source: products.ttAdapter() 
}); 

답변

0

은의 형식에 문제가 당신의 데이터.

이 문서에서 직접 올바른 형식의 JSON 파일입니다

당신이 적절한 형식으로 JSON의 몸을 포맷하는 필터 기능을 사용할 수있는 현재의 형식을 유지하려면 http://twitter.github.io/typeahead.js/data/nba.json. 나는 이것을 테스트하고 있지 않습니다

... 
prefetch: { 
    url: '/js/products.json', 
    filter: function(response){ 
    //format the data here 
    return response.Products 
    } 
} 

같이 보일 것이다

.

행운을 빌어 요.

+0

2 예는 여기에 필터 기능을 사용한다 : http://twitter.github.io/typeahead.js/examples/ – bottens

+0

하거나 시작하는 당신의 JSON 파일을 변경을 '['로 끝나고']로 끝납니다. 각 앨범은 그 안의 객체 '{...}'일 수 있습니다. – royhowie

+0

그가 그랬다면 제품은 그의 자료가 될 것이고, 실제로 그가 찾고자하는 것은 객체의 배열 인 제품의 가치입니다. 이것이 필터 함수를 만든 이유입니다. :) – bottens

3

아래 코드와 같이 응답을 필터링해야합니다. 는 선행 입력 사용을 위해 여기에 더 많은 예제를 참조 https://twitter.github.io/typeahead.js/examples/

prefetch: { 
    url: '/js/products.json', 
    filter: function (products) { 
      return $.map(products.Products, function (data) { 
       return { 
        name: data.name 
       }; 
      }); 
    } 
} 
관련 문제