简体   繁体   中英

Typeahead and Laravel not returning any results

I am trying to setup Typeahead.js, to use as an autosuggestion feature on my Laravel app. Unfortunately, it returns no results, each time.

I return the data beforehand to take advantage of local storage, so there is no querying the DB in my instance.

Route:

Route::get('/', function () {
    return view('welcome', ['treatments' => Treatment::orderBy('treatment')
        ->pluck('treatment', 'id')]);
});

Welcome view:

const treatments = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: '{{$treatments}}'
  });

  $('#bloodhound').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      name: 'treatments',
      source: treatments,

      templates: {
        empty: [
          '<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
        ],
        header: [
          '<div class="list-group search-results-dropdown">'
        ]

      }
    }).on('typeahead:selected', function (evt, item) {
    $('#bloodhound').text(item.id);
  });

Input field:

<input type="search" name="treatment" id="bloodhound" class="form-control" 
        placeholder="Find a treatment" autocomplete="off" required>

Output of $treatments array:

local: '{&quot;2&quot;:&quot;Treatment 1&quot;}'

The last section of the script, should enter the value of the selection (ID ) within the input field, but unfortunately that doesn't work either.

Many thanks.

Doesn't string local: '{&quot;2&quot;:&quot;Treatment 1&quot;}' seem strange to you?

First, it is sent through htmlspecialchars and all your quotes became &quote; , second - value of local is a string. Do you think, typeahead can understand what you have here?

Solution: get your elements form database and output'em json-encoded. To avoid quotes escaping use {!! !!} {!! !!} :

const treatments = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: {!! $treatments !!}
});

Route:

Route::get('/', function () {
    return view(
        'welcome', 
        ['treatments' => Treatment::orderBy('treatment')->pluck('treatment', 'id')->toJson()]
    );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM