简体   繁体   中英

How can I access JSON passed from PHP Laravel it in JS?

View

Right now, when I do

<pre>{{ $device->window }}</pre>

I see this

在此处输入图像描述


I want to access it in JS. Ex. device.screen.height , It's 926

I've tried

console.log(`{{ json_decode($device->window) }}`);
console.log(JSON.parse(`{{ json_decode($device->window) }}`));
console.log(JSON.parse(`{{ json_decode($device->window) }}`));
console.log(JSON.stringify(`{{ json_decode($device->window) }}`));
console.log(JSON.stringify(`{{ json_decode($device->window) }}`));
console.log(JSON.parse(`{{ json_encode($device->window) }}`));
console.log(JSON.parse(`{{ json_encode($device->window) }}`));
console.log(JSON.stringify(`{{ json_encode($device->window) }}`));
console.log(JSON.stringify(`{{ json_encode($device->window) }}`));

I kept getting

htmlspecialchars() expects parameter 1 to be string, object given


If I do:

console.log(JSON.parse(JSON.stringify( {{ json_encode($device->window) }} )));

I got

&quot;{&quot;innerWidth&quot;:&quot;980&quot;,&quot;innerHeight&quot;:&quot;1708&quot;,&quot;devicePixelRatio&quot;:&quot;3&quot;,&quot;screen&quot;:{&quot;width&quot;:&quot;428&quot;,&quot;height&quot;:&quot;926&quot;}}&quot;

I got so many &quot;

You have to use different sintax for that:

{!! json_encode($device->window) !!}

But you should not access it like this. Its not good practice to mix languages.

Inside a script tag, you could do:

const myData = {{ $device->window }};
console.log(myData.screen.height);

The's a blade directive for that:

@php
    $json = [ 1, new DateTime, (object)[], 'a' ];
@endphp
<script>
    test = @json($json);
    console.log(test)
</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