简体   繁体   中英

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. 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.

var dicomarray = '{{ json_encode($dicomfilearray) }}';
console.log(dicomarray);

And the following is a log result from the 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

$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. Actually, I just read your comment. If in Ajax

so I suggest send array with json_encode and populate that data into view with javascript. simply right below in controller

response()->json(['status'=>200,'data'=>$dicomfilearray])

Update So ,you not sending ajax request so, simply. do like below.

controller:-

$data = json_encode($dicomfilearray);
    return view('your-view',compact('data'));

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. All you have to do is to call the init function with passed parameters.

 <script>      
    $(function () {
         init({{ json_encode($dicomfilearray) }} });
         function init(dicomfilearray){
        //use your variable here  
      }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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