使用 PDO MySQL 查询将字符串传递给 javascript

Passing string to javascript with a PDO MySQL query

我有一个 table,其中包含 'banned_ip' 和 'reason' 列,我正在尝试显示特定于被禁止用户的错误消息。出于某种原因,显示 $row['reason'] 似乎有问题。有任何想法吗?

PHP:

$stmt = $conn->prepare('SELECT * FROM blackList WHERE banned_ip = :ip');
$stmt->execute(array('ip' => $_SERVER['REMOTE_ADDR']));

foreach ($stmt as $row) {
    echo "<script language='javascript'> displayBanError('" . $row['reason'] . "'); </script>";
}

JS:

function displayBanError(reason) {
    document.getElementById('error_field').innerHTML = "<p>Error: This IP has been blacklisted.<br>Reason: " + reason + "</p>";
}

将纯 PHP 与 JavaScript 混合可能会很糟糕,因为所有这些引号和其他字符都需要转义。尝试将 PHP -> JS 字符串 base64-encoded in PHP, in JS there are functions to decode it 传回可读形式。

...或尝试 Smarty.