简体   繁体   English

Laravel JavaScript将数组从后端传递到JavaScript中的数组

[英]Laravel JavaScript passing an array from backend to a array in JavaScript

I have a controller that passes a array to the blade file call it $data From there I echo the data to the page via blade like {{ $data[0]['name] }} 我有一个控制器将一个数组传递给刀片文件调用它$ data从那里我通过刀片将数据回显到页面,如{{$ data [0] ['name]}}

The problem is I also want the data to be inside an array in javascript. 问题是我也希望数据在javascript中的数组中。

How can this be accomplished? 如何实现这一目标? Is it best to just request the data again via AJAX or is there a way to get the data out of blade and into javascript. 最好是通过AJAX再次请求数据,还是有办法从刀片和javascript中获取数据。 Or possible rendering it to html in JSON via Blade then pulling the JSON from the html in JavaScript 或者可以通过Blade将其渲染为JSON中的html,然后从JavaScript中的html中提取JSON

So in doing this, you'd simply pass the data to javascript the same way you would with php: <script> var a = ['{{$data[0]['name] }}','{{$data[0]['name] }}'];</script> 因此,在执行此操作时,您只需将数据传递给javascript,就像使用php一样: <script> var a = ['{{$data[0]['name] }}','{{$data[0]['name] }}'];</script>

Or, if you don't want to go through each individual one and add them by hand, use laravels built in foreach loop: 或者,如果您不想浏览每个单独的并手动添加它们,请使用foreach循环中构建的laravels:

var a = [@foreach($data as $k => $info)
   '{{ $info }}',
@endforeach ]

This just depends on exactly how you plan on going about this 这完全取决于你打算如何计划

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM