为什么这不起作用? 在JS中回应PHP [关闭]

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);">

Look at the output of your PHP:

var check = lol;

lol is an undefined variable.

If you want to generate JavaScript with a string in it, then you have to generate the syntax for a string literal.

The json_encode function will do this (while escaping any characters that need escaping for JS).

var check = <?php echo json_encode('lol'); ?>;

If you are using a .php file

<script type="text/javascript">
var check = '<?php echo "lol"; ?>';
</script>

<input type="submit" value="click me" onClick="document.write(check);">

If you are not using a .php file then php code will not work.

<script type="text/javascript">
    var check = 'lol';
    </script>

<input type="submit" value="click me" onClick="document.write(check);">