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);
在webconsole中,我得到:
SyntaxError: missing ; before statement
在firefox调试器中:
最佳答案
使用单引号代替var teachers = '<?= json_encode($teachers) ?>';
或根本不使用引号,而忽略了JSON.parse(teachers);
。
var teachers = <?= json_encode($teachers) ?>;
console.log(teachers);
尽管您必须检查
$teachers
是否有效,但始终应为字符串,空值或数组。否则它将变为
var teachers = ;
并中断。关于javascript - 解析Java语言中的Laravel JSON对象抛出错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46129008/