[英]How to pass variable from controller to javascript?
im working on a laravel project. 我正在开展一个laravel项目。 im trying to do auto-complete search box by retrieving data from the database.
我试图通过从数据库中检索数据来做自动完成搜索框。 not sure how to foreach the collection and get it working in js
不知道如何预先收集集合并使其在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>
update: im using the pluck update my view 更新:我使用pluck更新我的视图
var tag = {!! json_encode($tag) !!};
$(function() {
var content = [
{ title: tag }
// etc
];
$('.ui.search')
.search({
source: content
});
});
No need to json_encode 不需要json_encode
Just change your view file code as per below 只需按照以下更改您的视图文件代码即可
<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 got it working yay 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.