在JS警告框中无法逃脱php变量

时间:2015-03-19 10:56:41

标签: javascript php

听起来很愚蠢但是我浪费了几个小时来尝试转义包含帖子数据的这个php变量:

$post=array ( 'offers' => '90', 
'pn' => '2', 'ord' => 'price', 'category_select' => '', )

和html:

<td><a href="#" onclick="alert('<?php echo $post;?>')">Look</a></td>

如何逃避它并获取发布数据的提醒? 感谢

2 个答案:

答案 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)

这有很多部分:

  1. 将数组转换为字符串

  2. 使用反斜杠转义任何'字符,因为您在由'字符分隔的JavaScript字符串中输出

  3. 使用htmlspecialchars是因为您在HTML属性中输出了这个内容,因此任何HTML特殊字符都需要转义,特别是(在我们的例子中)" =&gt; &quot;

  4. 所以:

    <a href="#" onclick="alert('<?php echo htmlspecialchars(str_replace("'", "\\'", json_encode($post)))?>')">Look</a>
    

    如何分解:

    1. json_encode将数组转换为字符串。您可能希望为格式化执行其他操作,但这是演示它的简单方法。

    2. str_replace将字符串中的所有'转换为\\'以在JavaScript字符串中转义它们

    3. htmlspecialchars将{2}的双引号转义为&quot;,因为它出现在双引号的HTML属性中

    4. 完整的测试用例,有两种引号:

      <!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>