document.getElementById 对内部 html 的调用适用于 $_POST 和 $_GET 变量,但不


document.getElementById call to inner html works with $_POST and $_GET variables but not with ordinary php variables

我很困惑。我可以将 $_GET 或 $_POST 数组中的变量放入元素的内部 HTML 中,但我不能将普通 php 变量中的文本放入。这是我的代码:

$msg = "We don't recognize that password. Please try again.";
echo "<script>document.getElementById('alert').innerHTML='".$msg."';</script>";
//echo "<script>document.getElementById('alert').innerHTML='".$_POST['email']."';</script>";

注释掉的行效果很好,但使用 $msg 的行效果不佳。我也尝试过这个但没有成功,所以用纯旧文本替换也不起作用。

echo "<script>document.getElementById('alert').innerHTML='hello';</script>";

关于我还能尝试什么的任何想法?我想在屏幕上打印 $_POST 或 $_GET 变量以外的内容。

谢谢。

将 PHP 值转换为 Javascript 时使用json_encode()。它将确保正确引用和转义值。它还允许您将更多数组传输到JS(JSON是对象和数组的Javascript文字表示法的子集)。

echo "<script>document.getElementById('alert').innerHTML=".json_encode($msg).";</script>";

由于这引用了值,因此您无需在赋值的 JS 部分包含引号。

这是消息,它包含一个打破它的单引号

$msg = "We don't ...."
//            ^ here

你最终得到

document.getElementById('alert').innerHTML= 'We don't ...';
要么

逃离它,要么删除它,要么更换它!