call php var inside JS

时间:2015-06-26 09:41:15

标签: javascript php

Could you tell me why this is not working ?

<html>
<body>

<?php
$var1 = "hello";
echo $var1;
?>

<button type="button"
onclick="document.getElementById('demo').innerHTML = <?php echo(json_encode($var1)); ?>;">
HI</button>

<p id="demo"></p>

</body>
</html>

What should I do to be able to read the php variable from JS ? Thanks

3 个答案:

答案 0 :(得分:1)

  1. As $var1 is string, you need to wrap that in quotes.
  2. AS $var1 is string and not array or object, json_encode is not required.

Use quotes around the string(See the marked positions for quotes):

onclick="document.getElementById('demo').innerHTML = '<?php echo($var1) ?>'">
//                                         ^                              ^

答案 1 :(得分:1)

It is a string. The 's needed to added properly around the string.

onclick="document.getElementById('demo').innerHTML = '<?php echo(json_encode($var1)); ?>';"

答案 2 :(得分:0)

Despite there are many answers, I will give my 2 cents about what I think the OP was thinking:

The basic idea was using json_encode to make the hello string to print "hello" instead of hello. The problem is actually that it will result in:

onclick="document.getElementById('demo').innerHTML = "hello";"

Which is NOT valid because of double quotes inside of double quotes.

Hence he can keep using json_encode if he wants to, as long as he changes the double quotes to single quotes:

onclick='document.getElementById("demo").innerHTML = <?php echo json_encode($var1); ?>;'
        ^ <-- single quote       ^----^ <-- double quote here     single there too --> ^

This should result in a valid output, which is:

onclick='document.getElementById('demo').innerHTML = "hello";'