douhanzhuo6905 2017-12-05 08:18 采纳率: 100%
浏览 152
已采纳

将带双引号的字符串作为参数从php传递到javascript

I've been trying to figure this thing out and I don't know what I'm doing wrong or maybe I'm missing something.

I'm trying to pass a string which contains double quotes that I retrieved from my database to be displayed in a textarea.

Situation sample looks like this:

<?php
   $content = '<div align="center"><b>This is a sample content.</b></div>';
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction('.$content.')">Click me</button>';
?>

<script>
  function myFunction(content){
    document.getElementById("myTextArea").innerHTML = content;
  }
</script>

Expected results should be that myTextArea should contain the text, but the result shows:

Output

Your help is greatly appreciated.

  • 写回答

2条回答 默认 最新

  • doubi6215 2017-12-05 08:25
    关注

    You should quote your output using htmlspecialchars(), such that it reads:

    <?php
       $content = "<div align=\"center\"><b>This is a sample content.</b></div>";
       echo '<textarea id="myTextArea"></textarea>';
       echo '<button onclick="myFunction(\''.htmlspecialchars($content).'\')">Click me</button>';
    ?>
    
    <script>
      function myFunction(content){
        document.getElementById("myTextArea").innerHTML = content;
      }
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?