【问题标题】:Laravel use json from controller in jqueryLaravel 在 jquery 中使用来自控制器的 json
【发布时间】:2016-10-03 08:36:42
【问题描述】:

我对 laravel 还很陌生,我正在尝试使用 laravel 复制我不久前在 wordpress 中构建的东西。所以我的目标是从数据库中查询一些数据,并在我的jQuery中使用这些数据的json_encode。

所以在我的控制器中我这样做了:

public function index()
    {
        $kalenderItems = Kalender::orderBy('created_at', 'desc')->get();
        $json = json_encode($kalenderItems);

        return view('kalender.index', compact('json'));
    }

在我看来,如果我这样做:

{{ $json }} 

它显然有效,但是当我尝试在同一个索引文件中的脚本标签中执行此操作时,它不起作用。很遗憾。

$items = {{ $json }};

我可以在我的脚本标签中像这样在 WordPress 中做到这一点

$items = <?php json_encode($data); ?>;

我可以在 laravel 中复制这个还是我尝试的不可能?

提前非常感谢!!

【问题讨论】:

  • $items = "{{ $json }}";

标签: php jquery json laravel


【解决方案1】:

您需要像这样将变量输出为原始变量:

<script>
var $items = {!! $json !!};
</script>

通过使用{{ $json }},该值将使用 HTML 实体进行编码,这会破坏 JSON。

【讨论】:

  • 非常感谢朋友!
猜你喜欢
  • 2020-01-04
  • 2022-01-20
  • 2016-06-15
  • 2015-12-15
  • 1970-01-01
  • 2019-12-14
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多