在Javascript抛出错误中解析Laravel JSON对象

时间:2017-09-09 09:07:35

标签: javascript php json laravel

Laravel代码:

$teachers = Teachers::where('possessed_by_community', $communityId)->pluck('teacher_name');

return view('pages.show_add_teachers', [
    'teachers'  => $teachers
]);

然后在客户端我尝试了:

var teachers = "<?php echo json_encode($teachers) ?>" ;
teachers = JSON.parse(teachers);
console.log(teachers);

在网络控制台中,我得到:

SyntaxError: missing ; before statement

在firefox调试器中:

enter image description here

2 个答案:

答案 0 :(得分:1)

使用单引号代替var teachers = '<?= json_encode($teachers) ?>';

或根本不使用引号,省略JSON.parse(teachers);

var teachers = <?= json_encode($teachers) ?>;
console.log(teachers);

虽然您必须始终检查$teachers是否有效,字符串,null或数组。

否则它会变成var teachers = ;并且会中断。

答案 1 :(得分:0)

var jArray = @json($teachers);