如何以JSON格式输出pdo结果以用于javascript函数?

时间:2018-12-05 16:56:32

标签: javascript json pdo

当我在PHP中回显结果时,它们似乎正确地格式化为JSON,但是当我回显将其保存在JavaScript中的变量时,我收到“未捕获的SyntaxError:意外的标识符”错误(当我删除echo语句)。这是代码:

$charset="utf8";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

$page = 'nike';
$stmt = $pdo->prepare('SELECT `url`, `alt`, `model`, `desc` FROM images WHERE page_id = (select id from pages where title = ?)');
$stmt->execute([$page]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'results are:' . $results; //array
$json = json_encode($results);
echo 'json is: ' . $json;// seemingly correct json formatted result set  

如果我像这样直接在JavaScript内部回显$json变量:

var imgs="<?php echo $json; ?>";

我收到“未捕获的SyntaxError:意外的标识符”错误消息,当我删除该行时,该消息消失。 我的JavaScript函数期望var imgs为:

var imgs = [
    {"url": "images/adidas_large/1.png", "model": "Kumacross", "desc": ""},
    {"url": "images/adidas_large/2.png", "model": "fig 2 model", "desc": "fig 2 desc"},
    {"url": "images/adidas_large/3.png", "model": "fig 3 model", "desc": "fig 3 desc"},
    {"url": "images/adidas_large/4.png", "model": "fig 4 model", "desc": "fig 4 desc"},
    {"url": "images/adidas_large/5.png", "model": "fig 5 model", "desc": "fig 5 desc"},
    {"url": "images/adidas_large/6.png", "model": "fig 6 model", "desc": "fig 6 desc"},
    {"url": "images/adidas_large/7.png", "model": "fig 7 model", "desc": "fig 7 desc"},
    {"url": "images/adidas_large/8.png", "model": "fig 8 model", "desc": "fig 8 desc"},
    {"url": "images/adidas_large/9.png", "model": "fig 9 model", "desc": "fig 9 desc"}
];

...,并且在提供此硬编码时有效。所以我的问题是,如何正确地以JSON格式输出PDO查询的结果以用于JavaScript函数?

1 个答案:

答案 0 :(得分:0)

我通过在JavaScript中而不是在php中进行json_encoding $ results来解决此问题并进行更改

var imgs = "<?php echo json_encode($results); ?>";

var imgs=<?php echo json_encode($results); ?>;