0

当我尝试将 PHP 变量回显到 JS 变量时,我总是得到“未捕获的语法错误:意外的标识符”。

<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);
}
4

1 回答 1

3

假设 JSON 是一个有效的 javascript 片段,我们为什么要把它用引号括起来呢?你期望数据会变成对象,但现在它变成了字符串。

做:

var data = <?php echo json_encode($serializedData) ?>;
于 2016-10-26T22:28:44.813 回答