简体   繁体   中英

How to get PHP string value in javascript?

Hi have looking on various questions but none of them seem to help me. I have a php variable in my php code and I am trying to access that in my javascript when I do. . .

var thing = "<?php echo($phpvariable); ?>";

then when I do

alert(thing);
It comes out to be "<?php echo($phpvariable); ?>" in the alert statement

What am I doing wrong?

Your PHP is obviously not being parsed. Are you in a .php file? If you're in a .js file, you'll need the server to parse those (or, more safely, put the PHP part somewhere in the DOM that the JS can access)

However, you're doing it wrong:

var thing = <?php echo json_encode($phpvariable); ?>;

Note: no quotes. json_encode will take care of that for you.

If this code is in a function in javascirpt that executes on click or at a specific event, then:

You are writing PHP Syntax in javascript, there is no way that you load the page then you run the php code. PHP code runs on the server side, so before any other HTML Javascript code executes

Else if you want to dynamically set the variable thing in javascript when the page is first loaded, then most probably you meant to write in the php file:

var thing = <?php echo '"'.$phpvariable.'"'; ?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM