How can I properly interpolate a variable as the value of a generated JavaScript value?
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.
精彩评论