Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

how to access PHP variables from within JavaScript?

I want to access PHP(server side file variables) with JavaScript(Client side script) without using MySQL. e.g. i have $name=Tom; How do i access this $name variable in JavaScript? Please show code example as i am new to programming. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do something like

<script>
    php_variable = <?= json_encode($php_variable) ?>;
</script>

which should even let you do arrays and possibly objects. It requires PHP 5.2 or later, though. If you're stuck without json_encode, you could wrap quotes around a call to addslashes, but that won't let you do arrays and such.

If your intent is to set the value within some form, you can do like

<input type="text" name="stuff" value="<?= htmlentities($stuff) ?>">

and of course, you could access that element's value within your script if necessary.

Two key points to take away here:

  • Since PHP is generating the page, it can output stuff as it pleases -- even right in the middle of a <script> element. You can use this to transfer variables from server to client, but not vice versa. (Transferring client variables...well...that's effectively going to require XHR or a form submit.)

  • But always* escape stuff going from PHP to anywhere -- particularly if it's going into HTML, JS, or directly into SQL. Unless you have your server set all retarded (enabling magic quotes, for example), PHP will get the data raw, and it could have special chars that will cause one or all of those to break.

* Ok, not quite always. If you have a PHP variable that contains some HTML or JS you want to output as HTML/JS, then don't escape it. But you should be aware of what "XSS" means, and don't blindly output data supplied by a user.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...