【问题标题】:Typeahead and Laravel not returning any resultsTypeahead 和 Laravel 没有返回任何结果
【发布时间】:2017-09-13 19:37:45
【问题描述】:

我正在尝试设置 Typeahead.js,以用作我的 Laravel 应用程序的自动建议功能。不幸的是,它每次都没有返回任何结果。

我事先返回数据以利用本地存储,因此我的实例中没有查询数据库。

路线:

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

欢迎观看:

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 type="search" name="treatment" id="bloodhound" class="form-control" 
        placeholder="Find a treatment" autocomplete="off" required>

$treatments 数组的输出:

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

脚本的最后一部分,应该在输入字段中输入选择的值 (ID),但不幸的是,这也不起作用。

非常感谢。

【问题讨论】:

    标签: php laravel laravel-5 typeahead.js bootstrap-typeahead


    【解决方案1】:

    你不觉得字符串local: '{&amp;quot;2&amp;quot;:&amp;quot;Treatment 1&amp;quot;}' 很奇怪吗?

    首先,它是通过htmlspecialchars 发送的,你所有的引号都变成了&amp;quote;,第二个-local 的值是一个字符串。你认为,typeahead 能理解你这里有什么吗?

    解决方案:从数据库中获取元素并输出 json 编码。为避免引号转义,请使用 {!! !!}:

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

    路线:

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

    【讨论】:

    • 感谢您的回复,现在避免引号转义会产生更有意义的内容: local: '{"2":"Treatment 1"}}' 虽然当我搜索它时仍然找不到@u_mulder?
    • 删除视图中$treatments开头和结尾的单引号。
    • local: {!! $treatments !!} 是我现在在脚本中的内容。这就是你的意思@u_mulder?
    • 是的,我是认真的。
    • 好吧,可惜还是没有返回结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    相关资源
    最近更新 更多