Pass PHP Array to JSON and JS: Uncaught SyntaxError: Unexpected identifier
Pass PHP Array to JSON and JS: Uncaught SyntaxError: Unexpected identifier
当我尝试将 PHP 变量回显到 JS 变量时,我总是得到 "Uncaught SyntaxError: Unexpected identifier"。
<script type="text/javascript">
$(function () {
var options = {
float: false,
removable: '.trash',
removeTimeout: 100,
acceptWidgets: '.grid-stack-item',
resizable: { handles: 'e, se, s, sw, w' }
};
$('#grid').gridstack(options);
var data = "<?php echo json_encode($serializedData); ?>";
我的PHP:
$serializedData = array();
$str = "SELECT gri_id as 'id', gri_plugin as 'plugin', gri_gridContent as 'content', gri_gridPosX as 'x', gri_gridPosY as 'y', gri_gridSizeX as 'width', gri_gridSizeY as 'height' FROM tGrid WHERE gri_location = '$loc'";
$stmt = $db->prepare($str);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $value) {
$function = $value["plugin"];
$data = $function($value['id'], $db);
$value['content'] = $data;
array_push($serializedData, $value);
}
假设 JSON 是 javascript 的有效片段,我们为什么要将其括在引号中?您希望数据会变成对象,但现在它变成了字符串。
做:
var data = <?php echo json_encode($serializedData) ?>;
当我尝试将 PHP 变量回显到 JS 变量时,我总是得到 "Uncaught SyntaxError: Unexpected identifier"。
<script type="text/javascript">
$(function () {
var options = {
float: false,
removable: '.trash',
removeTimeout: 100,
acceptWidgets: '.grid-stack-item',
resizable: { handles: 'e, se, s, sw, w' }
};
$('#grid').gridstack(options);
var data = "<?php echo json_encode($serializedData); ?>";
我的PHP:
$serializedData = array();
$str = "SELECT gri_id as 'id', gri_plugin as 'plugin', gri_gridContent as 'content', gri_gridPosX as 'x', gri_gridPosY as 'y', gri_gridSizeX as 'width', gri_gridSizeY as 'height' FROM tGrid WHERE gri_location = '$loc'";
$stmt = $db->prepare($str);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $value) {
$function = $value["plugin"];
$data = $function($value['id'], $db);
$value['content'] = $data;
array_push($serializedData, $value);
}
假设 JSON 是 javascript 的有效片段,我们为什么要将其括在引号中?您希望数据会变成对象,但现在它变成了字符串。
做:
var data = <?php echo json_encode($serializedData) ?>;