正确组合转义字符以将PHP注入javascript中? [英] Correct combination of escape characters to inject PHP in javascript?
问题描述
我尝试了所有我知道的组合,但无法正确完成!
I've tried all the combination I know of but can't get it right!
echo <<<EOF
<a href="javascript:popup('$comments')">Popup!</a>
EOF;
我想将$ comments中包含的字符串传递给弹出窗口,但是我似乎无法获得转义字符和串联的正确组合.请帮助!
I want to pass the string that is contained in $comments to the popup, but I can't seem to get the right combination of escape characters and concatenation. Help pls!
TIA
这是进入我提到的字符串的HTML.
This is the HTML that goes into the string I mentioned.
$comments.= "<b>" . $row['comName'] . "</b><br><i>" . $row['comment'] . "</i><br><br>";
推荐答案
您需要先将字符串转义为有效的Javascript/JSON以保留Javascript语法,然后对Javascript转义以保留其嵌入的HTML的语法:
You need to escape the string to valid Javascript/JSON first to preserve Javascript syntax, then escape the Javascript to preserve the syntax of the HTML it's embedded in:
$js = sprintf('javascript:popup(%s)', json_encode($comments));
printf('<a href="%s">Popup!</a>', htmlspecialchars($js));
因为这很痛苦,所以您应该真正尝试使用 不引人入胜的JavaScript ,它将Javascript与HTML分开.
Since this is quite a pain, you should really try to go for unobtrusive Javascript, which separates Javascript from HTML.
这篇关于正确组合转义字符以将PHP注入javascript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!