开发者

How can I properly interpolate a variable as the value of a generated JavaScript value?

开发者 https://www.devze.com 2022-12-23 14:51 出处:网络
I can\'t change the value of the text field (with the id \"code\") to the PHP value (stored in the variable $code):

I can't change the value of the text field (with the id "code") to the PHP value (stored in the variable $code):

$code = $_POST['code'];
echo "<script language='javascript'>
document.getElementById('code').value = $c开发者_如何学Goode </script>";

I also tried '$code' and "$code","..." + "%code + "...", but neither helped. What am I doing wrong?


Does $code contain a string? If so you'll need to quote it.

e.g. if $code equals "my test string", the Javascript will be output like:

$code = $_POST['code'];
echo "<script language='javascript'>
document.getElementById('code').value = my test string </script>";

which is invalid Javascript.

You need to:

$code = str_replace("'", "\'", $_POST['code']);
echo "<script language='javascript'>
document.getElementById('code').value = '$code' </script>";

I would also do:

$code = str_replace("'", "\'", htmlspecialchars($_POST['code']));

htmlspecialchars quotes HTML characters to prevent XSS attacks.


Try this :

$code = $_POST['code'];
echo "<script language=\"javascript\">
document.getElementById(\"code\").value =". $code. "</script>";

Or better yet :

<?php
$code = str_replace("'", "\'", htmlspecialchars($_POST['code']));
?>

<script type="text/javascript">
document.getElementById("code").value = "<?php echo $code;?>";//OR <?= $code;?>;
</script>


.value = $code

to

.value = '".str_replace("'", "\'", $code)."'


PHP doesn't see the $code as you've written it. Use this instead:

$code = $_POST['code'];
echo "<script language='javascript'>
document.getElementById('code').value = ".$code."; </script>";

or

$code = $_POST['code'];
echo "<script language='javascript'>
document.getElementById('code').value = {$code}; </script>";

Either more explicitly allows PHP to recognise and parse your string.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号