在JavaScript和PHP中转义引用

oca*_*nal 0 javascript php string escaping

<?php
    /* ... Getting record from database */

    $comment = $record["comment"];
    /* There might be quotes or double quotes, we don't know */

    echo "<input type='button' onclick=\"doSomething('$comment')\" />";
?>

<script>
    function doSomething(comment) {
        alert(comment);

        /* Something else */
    }
</script>
Run Code Online (Sandbox Code Playgroud)

当$ comment字符串包含单引号时,我在javascript中收到" Uncaught SyntaxError:Unexpected token ILLEGAL "错误.

  • 我在引号之前添加斜杠,它没有用 - $comment = str_replace("'","\'",$comment);

在这个例子中,如何逃避报价和双引号?

Mar*_*c B 9

使用json_encode(),它保证您的输出将是语法上有效的JavaScript代码:

<input type="button" onclick="doSomething(<?php echo json_encode($comment) ?>">
Run Code Online (Sandbox Code Playgroud)