问题描述
我正在寻找逃避PHP中一些Javascript文本的最佳方法,并且 json_encode
是错误的工具。
I'm looking for the best way to escape some Javascript text in PHP, and json_encode
is the wrong tool for the job.
问题来自这一行:
The problem comes from this line:
echo " onclick=\"SwitchDiv('" . $option . "')\"";
如果 $ option
中有撇号,这是一个多汁的客户端 - 失败。但直接 json_encode
(在其他情况下运行良好)无济于事:
If there's an apostrophe in $option
, this is a juicy ball of client-side fail. But doing a straight json_encode
(which works perfectly well in other contexts) doesn't help:
echo " onclick=\"SwitchDiv(" . json_encode($option) . ")\"";
创建输出字符串 onclick =SwitchDiv(Athle's foot)
,导致 onclick
值提前终止。 (如果我用单引号括起 onclick
值,也会发生这种情况。)
That creates an output string of onclick="SwitchDiv("athlete's foot")"
, resulting in premature termination of the onclick
value. (Which also happens if I enclose the onclick
value in single quotes.)
这是否有一种优雅的方式?我是否应该通过正在使用单引号转义的正则表达式来输出 json_encode
输出?
Is there an elegant way around this? Should I just funnel the json_encode
output through a regex that will escape the single quotes?
推荐答案
json_encode
是这项工作的正确工具。您的问题源于您还在 HTML属性中包含该Javascript,因此它还需要 htmlspecialchars
-encoded。
json_encode
is the right tool for the job. Your problem arises from the fact that you are also including that Javascript in an HTML attribute, thus it also needs to be htmlspecialchars
-encoded.
echo " onclick=\"SwitchDiv(" . htmlspecialchars(json_encode($option)) . ")\"";
这篇关于在PHP中转义Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!