[英]How to get array from controller on javascript blade in Laravel
I'm working on a laravel project and am trying to pass an array from a controller to javascript. 我正在做一个laravel项目,正在尝试将数组从控制器传递到javascript。 The following code is from my controller. 以下代码来自我的控制器。
$dicomfilearray = $dicom->pluck('filename')->toArray();
return view('xray.view')->withDicomfilearray($dicomfilearray);
And below is the Javascript in that's in the blade file I'm trying to pass it to. 下面是我试图将其传递到刀片文件中的Javascript。
var dicomarray = '{{ json_encode($dicomfilearray) }}';
console.log(dicomarray);
And the following is a log result from the Javascript. 以下是Javascript的日志结果。
["storage/uploads/storeid1/27/10/dicom/c4p4Oco3rU.dcm","storage/uploads/storeid1/27/10/dicom/RNil0NPPzQ.dcm"]
I would like to get a list from this array. 我想从此数组获取列表。 Any advice or guidance on this would be greatly appreciated, Thanks. 对此,任何建议或指导将不胜感激。
You can make ajax call in frotend, and backend do like this 您可以在frotend中进行ajax调用,而后端可以这样做
$dicomfilearray = json_encode($dicom->pluck('filename'))->toArray());
return view('xray.view')->withDicomfilearray($dicomfilearray);
when you working in javascript and need data in javascript then why you need view
part. 当您使用javascript工作并且需要javascript数据时,为什么需要view
部件。 Actually, I just read your comment. 实际上,我只是读过您的评论。 If in Ajax 如果在Ajax中
so I suggest send array with json_encode
and populate that data into view with javascript. 因此,我建议使用json_encode
发送数组,并使用javascript将数据填充到视图中。 simply right below in controller 只需在控制器下方
response()->json(['status'=>200,'data'=>$dicomfilearray])
Update So ,you not sending ajax request so, simply. 更新所以,你不发送Ajax请求的话,干脆。 do like below. 做如下。
controller:- 控制器:-
$data = json_encode($dicomfilearray);
return view('your-view',compact('data'));
javascript javascript
var dicomarray = '{{ $data }}';
You can do something like this and this even works if you want to pass the variable to external javascript file. 您可以执行类似的操作,并且如果要将变量传递给外部javascript文件,这甚至可以工作。 All you have to do is to call the init function with passed parameters. 您要做的就是调用带有传递参数的init函数。
<script>
$(function () {
init({{ json_encode($dicomfilearray) }} });
function init(dicomfilearray){
//use your variable here
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.