PHP/ Javascript inserting html with ' and " to a javascript function from PHP
I have HTML in a database which I want to show with facebox (jquery popup). I use the PHP code below to render the button that launches the facebox
$html.="<img onclick='$.facebox(\"".$db_data[html]."\");' src='img.png' />";
How can I escape things properly so that facebox will get also ' and " in $db_data[html]? (for example if the html inc开发者_如何学Cludes styles?)
Use json_encode
to convert the string properly to a JavaScript compatible string and htmlspecialchars
to encode it for the use in an HTML attribute value:
"<img onclick='" . htmlspecialchars("$.facebox(".json_encode($db_data['html']).");", ENT_QUOTES) . "' src='img.png' />"
Note the use of the quote style ENT_QUOTES to also encode '
that are used to quote the attribute value. This wouldn’t be necessary if you would use "
for the HTML attribute value instead:
'<img onclick="' . htmlspecialchars("$.facebox(".json_encode($db_data['html']).");") . '" src="img.png" />'
精彩评论