简体   繁体   English

使用引号引起的错误

[英]error using quote marks

I have the code below: 我有下面的代码:

<head>
    <title>Quote Marks</title>
</head>
<body>

<?php
    $variable1 = "'QUOTE' \" 'MARKS'";
?>

    <button onclick="text( '<?php  echo addslashes($variable1); ?>' );">click me</button>

    <script type="text/javascript">
        function text(texto){
            if( confirm( texto ) ) {
                alert("thanks!");
            }
        }
    </script>

</body>

It don't work! 没用! I'm having problems with the quote marks... When i click the button, i want the dialog showing the text in "$variable1" with all quotes... 我的引号出现问题...单击按钮时,我希望对话框显示"$variable1"中的所有引号...

You need to make the data: 您需要进行数据:

  • A safe JavaScript string — use json_encode instead of ' , addslashes , and ' . 一个安全的JavaScript字符串—使用json_encode代替'addslashes'
  • A safe HTML attribute value — use htmlspecialchars 安全的HTML属性值-使用htmlspecialchars

Thus: 从而:

<button 
    onclick="text(<?php echo htmlspecialchars(json_encode($variable1)); ?>);">

As a rule of thumb, dealing with PHP quotes inside JavaScript quotes inside HTML quotes is more trouble then it is worth. 根据经验,处理PHP引号和HTML引号内的JavaScript引号要麻烦得多,这值得。 You can usually get rid of at least one level of nesting by keeping your JS in a <script> element instead of inside attribute values. 通过将JS保留在<script>元素而不是内部属性值中,通常可以消除至少一层嵌套。

<script>
    function myFunction() {
        text(<?php echo json_encode($variable1); ?>);
    }
    document.querySelector('button').addEventListener('click', myFunction);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM