简体   繁体   中英

Laravel - How to pass a php variable to a javascript function from a blade file

I have an html element inside my blade file:

<input id="check_all" onclick="toggleCheckOrders('$orderFormObject', ' $count')" name="check_all" type="checkbox" value="1">

The onclick handler is assigned a javascript function toggleCheckOrders which accepts two parameters which are objects that were passed from the controller to the blade template. When I do this, it just treats them as strings inside the javascript function, it there a way to pass them while retaining their respective data types?

You should use:

<input id="check_all" onclick="toggleCheckOrders('{{ $orderFormObject }}', ' {{ $count }}')" name="check_all" type="checkbox" value="1">

In Blade you use {{ ... }} to echo variable value

Here's a little helper I wrote for myself:

I added this in my AppServiceProvider.php :

 Blade::directive('jsvar', function ($expression) {
     return "<?php echo json_encode($expression); ?>";
 });

This will allow you to do:

<input id="check_all" onclick="toggleCheckOrders(@jsvar($orderFormObject), @jsvar($count))" name="check_all" type="checkbox" value="1">

If you find yourself passing PHP variables to JavaScript often I highly recommend this approach.

you can simply do

<input id="check_all" onclick="toggleCheckOrders({{json_encode($orderFormObject)}}, {{ json_encode($count)}})" name="check_all" type="checkbox" value="1">

carefull that associative array will be casted as object in JavaScript

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