[英]How to pass variable from php to javascript, as attribute?
I want to pass a variable from php to HTML as "attribute" so that javascript (jQuery) could access that. 我想将变量从php传递给HTML作为“属性”,以便javascript(jQuery)可以访问该变量。
$variable = addslashes( this is the text, coming from database, which can contain '' ' ' ' ' or "" " " " "" " or even <br><hr> tags );
HTML: HTML:
<img id="clickMe" titleAttr="<?php echo $variable; ?>" />
JS: JS:
$('#clickMe').click(function() {
alert ($(this).attr('titleAttr'));
});
now Firefox say its a bad HTML code, and alert()
shows the text until the first ' signal (the rest is cut off) 现在Firefox说它的HTML代码错误,并且
alert()
一直显示文本,直到第一个'信号(其余信号被切断)
You want htmlspecialchars
not addslashes
. 您要
htmlspecialchars
而不是addslashes
。
There is almost always a better escaping mechanism than addslashes
for any situation, and when there isn't, addslashes
is rarely sufficient so you need to write one. 在任何情况下,总有一种比转义
addslashes
更好的转义机制,如果没有,转义addslashes
很少就足够了,因此您需要编写转义addslashes
。
addslashes
is particularly poor for inserting data into HTML since \\
is not an escape character in HTML. 对于在HTML中插入数据而言,
addslashes
特别差,因为\\
不是HTML中的转义字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.