简体   繁体   English

Typeahead和Laravel不返回任何结果

[英]Typeahead and Laravel not returning any results

I am trying to setup Typeahead.js, to use as an autosuggestion feature on my Laravel app. 我正在尝试设置Typeahead.js,以用作Laravel应用程序上的自动提示功能。 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: $treatments数组的输出:

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. 脚本的最后一部分应在输入字段中输入选择的值(ID),但不幸的是,这也不起作用。

Many thanks. 非常感谢。

Doesn't string local: '{&quot;2&quot;:&quot;Treatment 1&quot;}' seem strange to you? 您对local: '{&quot;2&quot;:&quot;Treatment 1&quot;}'字符串local: '{&quot;2&quot;:&quot;Treatment 1&quot;}'感到陌生吗?

First, it is sent through htmlspecialchars and all your quotes became &quote; 首先,它是通过htmlspecialchars发送的,所有报价都变成了&quote; , second - value of local is a string. ,第二-价值local是一个字符串。 Do you think, typeahead can understand what you have here? 您是否认为,提前输入可以理解您在这里拥有的东西?

Solution: get your elements form database and output'em json-encoded. 解决方案:从数据库中获取元素并以json编码输出。 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()]
    );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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