我需要将我的php数组转换为javascript变量。我正在使用json_encode执行此操作,但它返回时出现了一些错误。我有一个php变量:
<?php $damage_array = $listing->tire_detail->damage_details; ?>
打印出来的
Array ( [lf] => 4 [rf] => 9 [lrfo] => 22 [rrfo] => 19 [lrfi] => 22 [rrfi] => 19 [lrro] => 15 [rrro] => 10 [lrri] => 15 [rrri] => 10 )
然后在我的javascript中我有:
var damages = "<?php echo json_encode($damage_array); ?>";
打印到:
var damages = "{"lf":4,"rf":9,"lrfo":22,"rrfo":19,"lrfi":22,"rrfi":19,"lrro":15,"rrro":10,"lrri":15,"rrri":10}";
有人可以帮我清理一下,以便我的js变量是一个真正的数组吗?
答案 0 :(得分:4)
试试这个:
var damagesAsString = '<?php echo json_encode($damage_array); ?>'; // json string
var damages = JSON.parse(damagesAsString); // json object
答案 1 :(得分:1)
我想你可以这样做......
var damages = <?php echo json_encode($damage_array); ?>;