Why wouldn't this work? This is just an example but how would I echo PHP using onClick()?
<script type="text/javascript">
var check = <?php echo 'lol'; ?>;
</script>
<input type="submit" value="click me" onClick="document.write(check);">
Why wouldn't this work? This is just an example but how would I echo PHP using onClick()?
<script type="text/javascript">
var check = <?php echo 'lol'; ?>;
</script>
<input type="submit" value="click me" onClick="document.write(check);">
查看 PHP 的输出:
var check = lol;
lol
是一个未定义的变量。
如果要生成其中包含字符串的 JavaScript,则必须生成字符串文字的语法。
该json_encode
函数将执行此操作(同时转义任何需要为 JS 转义的字符)。
var check = <?php echo json_encode('lol'); ?>;
如果您使用的是 .php 文件
<script type="text/javascript">
var check = '<?php echo "lol"; ?>';
</script>
<input type="submit" value="click me" onClick="document.write(check);">
如果您不使用 .php 文件,则 php 代码将无法工作。
<script type="text/javascript">
var check = 'lol';
</script>
<input type="submit" value="click me" onClick="document.write(check);">