2017-09-13 196 views
0

我试图设置Typeahead.js,用作我的Laravel应用程序的自动提示功能。不幸的是,它每次都没有返回结果。Typeahead和Laravel不返回任何结果

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

路线:

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

Welcome视图:

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)的值,但不幸的是,不能正常工作。

非常感谢。

回答

0

不是字符串local: '{&quot;2&quot;:&quot;Treatment 1&quot;}'对你来说显得很陌生?

首先,它是通过htmlspecialchars发送并且所有报价变为&quote;,第二个值是local是一个字符串。你认为,键入可以理解你在这里?

解决方案:让您的元素形成数据库和output'em 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()] 
    ); 
}); 
+0

谢谢您的回复,避免了引号逃逸现在生产的东西更有意义:本地:“{ “2”: “处理1” }}'虽然当我搜索它@u_mulder时仍然无法找到? – Ben

+0

从视图中'$ treatments'的开头和结尾删除单引号。 –

+0

'本地:{!! $治疗!!}'是我现在在脚本中的。这是你的意思@u_mulder? – Ben