如何从PHP转义字符串为JavaScript? [英] How to escape string from PHP for javascript?

查看:167
本文介绍了如何从PHP转义字符串为JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

,它会导致

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

,这使JS无法工作,因此它会遗失代码。使用单个qoute '它可以正常工作。 mysql真正的逃避做同样的事情。
如何转义任何字符串,使其不会破坏javascript?

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

json_encode看起来不错,但是一定要做错事,它还是坏的:是Firefox看到的截图 - 它插入一个坏的双引号!该值只是一个简单的数字:

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:

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

我确实使用过:

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


推荐答案

<$应该像任何其他HTML属性一样转义c $ c> onclick 属性,使用 用htmlspecialchars() 。代码中的实际Javascript字符串应使用 json_encode() 。例如:

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

正在说... onclick(或任何其他事件)的属性是如此2005.自己一个好处,并将您的JavaScript代码与您的HTML代码,最好是外部文件分开,并使用DOM函数附加事件(或jQuery,它很好地包装)

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)

这篇关于如何从PHP转义字符串为JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆