如何从JavaScript中访问PHP变量?

问题描述:

我想使用JavaScript(客户端脚本)访问PHP(服务器端文件变量)而不使用MySQL。例如我有$ name = Tom;如何在JavaScript中访问此$ name变量?请显示代码示例,因为我是编程新手。谢谢。

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.

你可以这样做

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

甚至可以让你做数组和可能的对象。但它需要PHP 5.2或更高版本。如果你在没有 json_encode 的情况下被卡住了,你可以在调用 addslashes 的时候包装引号,但这不会让你做数组等等。

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.

这里有两个要点:


  • 由于PHP正在生成页面,它可以随意输出内容 - 甚至可以在< script> 元素的中间输出。您可以使用它将变量从服务器传输到客户端,但反之亦然。 (转移客户端变量......好吧......这实际上需要XHR或表单提交。)

  • 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.)

但总是*逃避从PHP到任何地方 - 特别是如果它进入HTML,JS或直接进入SQL。除非您的服务器设置为全部延迟(例如启用魔术引号),否则PHP将获取原始数据,并且它可能具有特殊字符,这将导致其中一个或所有字符中断。

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.

*好的,不是相当总是。如果您有一个包含某些HTML或JS的PHP变量,您希望将输出为 HTML / JS,那么请不要将其转义。但是你应该知道XSS的含义,并且不要盲目输出用户提供的数据。

* 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.