繁体   English   中英

在JavaScript数组中推送Laravel集合

[英]Push Laravel collection in a javascript array

我是Lavarel ,我编写了这部分代码,以将我的收藏集添加到javascript数组中,但这似乎不起作用。

$(document).ready(function() {

            var data = [];
            @foreach($products as $product )
                data.push({'{{ $product->id }}' : '{{ $product->name }}'});
            @endforeach

//            Im trying to get a variable which looks like this
//            data: [
//                {
//                    id: 'The ID goes here',
//                    text: 'Text to display'
//                },
//                // ... more data objects ...
//            ]
        });

请帮我解决这个问题

最好创建一个Laravel集合并将其转换为json,以便javascript可以读取。

var data = {{ $products->map(function ($product) { return ['id' => $product->id , 'text' => $product->name];})->toJson() }};

在您的控制器中生成此json字符串将更加干净。

为什么不在Laravel Controller中将集合转换为JSON:

$collectionArr = Collection::all()->toJson();

然后在HTML中回显它:

<script>
    var jsArray = {{$collectionArr}};
</script>

这是Laravel网站的更多信息: https ://laravel.com/docs/5.3/eloquent-serialization#serializing-to-json

您可以简单地写:

$(document).ready(function() {    
    var data = {!! json_encode($products) !!}; // Note the {!! !!} to not encode html entities since we'll probably have quotes in here                 
});

暂无
暂无

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

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