听起来很愚蠢但是我浪费了几个小时来尝试转义包含帖子数据的这个php变量:
$post=array ( 'offers' => '90',
'pn' => '2', 'ord' => 'price', 'category_select' => '', )
和html:
<td><a href="#" onclick="alert('<?php echo $post;?>')">Look</a></td>
如何逃避它并获取发布数据的提醒? 感谢
答案 0 :(得分:1)
<?php
$post=array ( 'offers' => '90',
'pn' => '2', 'ord' => 'price', 'category_select' => '', )
?>
<script>
alert('<?php foreach($post as $key=>$p) { echo $key . ": " . $p . ", "; } ?>');
</script>
这适用于我,你必须遍历数组以回应警报。
答案 1 :(得分:1)
这有很多部分:
将数组转换为字符串
使用反斜杠转义任何'
字符,因为您在由'
字符分隔的JavaScript字符串中输出
使用htmlspecialchars
是因为您在HTML属性中输出了这个内容,因此任何HTML特殊字符都需要转义,特别是(在我们的例子中)"
=&gt; "
所以:
<a href="#" onclick="alert('<?php echo htmlspecialchars(str_replace("'", "\\'", json_encode($post)))?>')">Look</a>
如何分解:
json_encode
将数组转换为字符串。您可能希望为格式化执行其他操作,但这是演示它的简单方法。
str_replace
将字符串中的所有'
转换为\\'
以在JavaScript字符串中转义它们
htmlspecialchars
将{2}的双引号转义为"
,因为它出现在双引号的HTML属性中
完整的测试用例,有两种引号:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<?php
$post=array (
'test_quotes' => 'I\'m "feeling" lucky',
'offers' => '90',
'pn' => '2',
'ord' => 'price',
'category_select' => '',
)
?>
<a href="#" onclick="alert('<?php echo htmlspecialchars(str_replace("'", "\\'", json_encode($post)))?>')">Look</a>
</body>
</html>