如何为 javascript 从 PHP 转义字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7085648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:47:15  来源:igfitidea点击:

How to escape string from PHP for javascript?

phpjavascriptescapingaddslashes

提问by user893856

lets imagine a form editor, it can edit available values. If the data contains "character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:

让我们想象一个表单编辑器,它可以编辑可用的值。如果数据包含"字符(双引号),它会“破坏”HTML 代码。我的意思是,让我们检查代码:所以我生成 HTML:

onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....

onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....

and it results in

它导致

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

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

and this makes JS work impossible, so that it ruins the code. With single qoute 'it works OK. mysql real escapedoes the same. How to escape any string so that it won't ruin javascript?

这使得 JS 无法工作,从而破坏了代码。使用单 qoute'可以正常工作。mysql real escape做同样的事情。如何转义任何字符串以使其不会破坏javascript?



json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:

json_encode 看起来不错,但我一定是做错了什么,它仍然很糟糕:这是 Firefox 如何看待它的屏幕截图 - 它插入了一个“坏”的双引号!该值只是一个简单的数字:

http://img402.imageshack.us/img402/5577/aaaahf.gif

http://img402.imageshack.us/img402/5577/aaaahf.gif

and I did used:

我确实使用过:

('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) { 

回答by shesek

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

onclick属性的值应该像任何其他 HTML 属性一样使用htmlspecialchars(). 代码中的实际 Javascript 字符串应使用json_encode(). 例如:

<?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(或任何其他事件)属性是如此 2005 年。帮自己一个忙,将您的 javascript 代码与您的 html 代码分开,最好是外部文件,并使用 DOM 函数(或 jQuery,它包装它很好)

回答by Marshall House

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>

回答by Marshall House

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

回答by Robin Winslow

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

我真的只是重新措辞@Marshall House 在这里所说的,但是:

In HTML, a double quote (") will alwaysend 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.

在 HTML 中,双引号 (") 将始终结束一个属性,而不管反斜杠 - 所以它看到:onclick="var a = prompt('New value: ', 'aaaa\"。@Marshall 提供的解决方案是将您的代码分离成一个函数。这样您就可以将转义的 PHP 打印到其中没有问题。

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