How to escape string from PHP for javascript?

强颜欢笑 提交于 2019-11-28 10:59:43
shesek

The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:

<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';

That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)

onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....

Your problem is highlighted in bold. You can't quote a variable declaration you shouldn't need to escape the double quote once this is removed since it is within single quotes. Should look like this -

onclick="newFunc();"
<script>
function newFunc()  {
var a = prompt('New value: ', 'aaaa"aaa'); 
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
    var a = prompt('new value:','<?php code; ?>');
    if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>

I'm really just re-wording what @Marshall House says here, but:

In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that @Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.

E.g.:

<script>
    // This is a function, wrapping your code to be called onclick.
    function doOnClickStuff() {
        // You should no longer need to escape your string. E.g.:
        //var a = prompt('new value:','<?php echo $rec[$i]; ?>');
        // Although the following could be safer
        var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
        if (a) { <!--javascript code--> }
        else { <!--javascript code--> }
    }
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!