[英]How to pass variable from controller to javascript?
我正在開展一個laravel項目。 我試圖通過從數據庫中檢索數據來做自動完成搜索框。 不知道如何預先收集集合並使其在js中運行
controller
$tag = DB::table('tags')->get(['title']);
view
//get each title for autocomplete
@foreach($tag as $key => $tag)
<p>{{$tag->title}}</p>
@endforeach
<script>
//im guessing im passing a tag collection right here??
//so how do i foreach tag->title variable right here in js to get the title only?
var tag = {!! json_encode($tag) !!};
$(function() {
var content = [
{ title: tag }
// etc
];
$('.ui.search')
.search({
source: content
});
});
</script>
更新:我使用pluck更新我的視圖
var tag = {!! json_encode($tag) !!};
$(function() {
var content = [
{ title: tag }
// etc
];
$('.ui.search')
.search({
source: content
});
});
不需要json_encode
只需按照以下更改您的視圖文件代碼即可
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script>
$(document).ready(function(){
var tag = {!! $tag !!} ;
console.log(tag); //here I console the tag data, you can use tag data as per your requirement
});
</script>
UPDATE FINAL讓它正常工作
<script>
$(document).ready(function(){
var tag = {!! $tag !!} ;
console.log(tag); //here I console the tag data, you can use tag data as per your requirement
var content;
var final="";
tag.forEach(function (item, key) {
//console.log(item);
var str1= "[";
var str2= "]";
var str3= '{ "title": "';
var str4= '"},';
var str5= '"}';
if (key==0) {
final = final + str1;
}
if (key+1!=tag.length) {
final= final+str3+item+str4;
}
else{
final= final+str3+item+str5+str2;
}
});
var obj = JSON.parse(final);
console.log(obj);
$('.ui.search')
.search({
source: obj
})
;
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.