简体   繁体   中英

Passing php variables to javascript in laravel syntax errors

Question 1) When passing PHP variables to be used in javascript if the variables hold an array, it will result in an error relating to the attempted conversion of array to string when trying to pass these values in the following manner. Why do I have to json encode the value before it works when $var itself is already an array?

PHP Code

$var = ['test'];

Javascript

Let var = {!!$var!!};

Solution

Let var = {!!json_encode($var)!!} 

Question 2 when passing PHP variables that may have the value of null to javascript, it may result in a syntax error. For example,

PHP Code

$var = null;

Javascript

Let var = {{$var}};

Error

Var = ; (Syntax error)

Failed Solution

if({{$var}}){
    let var = {{$var}};

Solution

Let var = '{{$var');

Why does my attempted solution of only setting the value of the var when $var has a value fails?

simply put laravel echo in doouble quote

<script>
 let var1="{{$var}}";
</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