I'm using Laravel Framework since a couple of weeks now.
I have a strange problem, I would like to convert a PHP 2D array into a JavaScript object, so I used in my controller json_encode() something like :
$arr['ping'] = array_values($arr['ping']);
$arr['doc'] = array_values($arr['doc']);
$data = json_encode($arr, JSON_HEX_QUOT);
Then, in my view file :
<div class="card-content">
{{ $data }}
</div>
<div id="chartPingListExpand" class="ct-chart"></div>
<script type="text/javascript">
$(document).ready(function() {
app.initChartPingListExpand({{ html_entity_decode($data) }}, {{ $maxping }});
});
</script>
Here is the thing : My {{ $data }}
shows correctly my json string
{"ping":[4,30],"doc":["2018-03-23 09:06:53","2018-03-23 01:04:23"]}
But Javascript doesn't like it :
Uncaught SyntaxError: Invalid or unexpected token
at this line
app.initChartPingListExpand({{ html_entity_decode($data) }}, {{ $maxping }});
And I think it's because HTML is translating quotes
by " ;
I've tried many ways to tell the html not to translate those quotes but it does not work, anybody has any idea ?
Maybe I can pass data to my Javascript function or any other way?
Your $data
is already a javascript object, you don't need to decode it
You can try if you put var obj = {{ $data }}; console.log(JSON.stringify(obj))
var obj = {{ $data }}; console.log(JSON.stringify(obj))
You should use JSON.stringify
which converts a JavaScript value to a JSON string
var data = JSON.stringify(jsonData);
Please visit this link for more details.
Note that Blade will try to protect you and will escape all unsafe characters. use
{!! $data !!}
to avoid that
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.