将数据传递给 javascript 但反斜杠太多

我正在将数据从我的控制器传递到 javascript。


public function index()

    {

        $events = Eventcalendar::get()->pluck('event');

        return view('eventcalendar.index',compact('events'));

    }

这是我在刀刃上做的


<script type="text/javascript">

  var data = {!! $events !!}


  console.log(data) //the result is in the screenshot

</script>

如何删除 JSON 数据中的反斜杠?


注意:事件列数据类型为 JSON


我正在使用 LARAVEL 7


谢谢

http://img2.mukewang.com/648eb9810001670706530042.jpg

慕码人2483693
浏览 117回答 4
4回答

胡说叔叔

你需要在控制器中解码你的 json&nbsp; public function index()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $events&nbsp; = json_decode(Eventcalendar::get()->pluck('event'));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return view('eventcalendar.index',compact('events'));&nbsp; &nbsp; &nbsp; &nbsp; }

互换的青春

根据Laravel 文档呈现 JSON有时,您可能会将一个数组传递给您的视图,目的是将其呈现为 JSON 以初始化 JavaScript 变量。例如:<script>    var events = <?php echo json_encode($events); ?>;</script>但是,您可以使用 @json Blade 指令而不是手动调用 json_encode。@json 指令接受与 PHP 的 json_encode 函数相同的参数:<script>    var events = @json($events);    var events = @json($events, JSON_PRETTY_PRINT);</script>

湖上湖

通过添加解决它protected&nbsp;$casts&nbsp;=&nbsp;[&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'event'&nbsp;=>&nbsp;'array' &nbsp;&nbsp;&nbsp;&nbsp;];

梵蒂冈之花

如果您可以控制后端代码,IE,您正在向后端发送请求,您可以添加JSON_UNESCAPED_SLASHES作为函数的第二个参数json_encode来停止转义字符,所以它应该看起来像这样:json_encode($res, JSON_UNESCAPED_SLASHES)。如果您必须在 Javascript 中处理此问题,则可以使用JSON.parse(string)并迭代数组中的每个条目。您可能会使用这样的东西;初始化一个新数组newData并将解析后的数据推入其中:var newData = []data.forEach(element => {&nbsp; newData.push(JSON.parse(element))})
打开App,查看更多内容
随时随地看视频慕课网APP