如何将变量从控制器传递到javascript?

时间:2019-05-28 18:25:53

标签: javascript laravel

我正在做一个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>

更新: 我正在使用拔毛 更新我的观点

var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });  
   });

2 个答案:

答案 0 :(得分:0)

无需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>

答案 1 :(得分:0)

最后更新 可以了

//popup.html
<label class="switch">
            <input type="checkbox" id="togBtn">
            <div class="slider round" id="thisthing">
                <span class="on">ON</span>
                <span class="off">OFF</span>
            </div>
        </label>