简体   繁体   English

从外部JS读取PHP文件变量

[英]Reading a PHP file variables from external JS

How may I retrieve, by JS (and I mean an external script), the value of some variables assigned in a php include file like the one below? 我如何通过JS(我的意思是一个外部脚本)来检索php包含文件中分配的某些变量的值,如下所示?

<?php 
    $var1 = "a";
    $var2 = "foo";
?>

Assuming that you mean using an AJAX request to retrieve the variables...the best way to do that would be: 假设您的意思是使用AJAX请求来检索变量...最好的方法是:

<?php
    $array["var1"]="a";
    $array["var2"]="foo";
    echo json_encode($array);
?>

And on the JS end, you would want to do: 在JS端,您需要执行以下操作:

json = eval( "(" + response + ")" );

And var1 and var2 would be json.var1/json.var2 var1和var2将是json.var1 / json.var2


Edit: 编辑:

In that case you should be able to do something like: 在这种情况下,您应该可以执行以下操作:

<script type="text/javascript">
    var phpvars = <?php echo json_encode($array); ?>;
<script>

And just place that above where whistle.js will be included, and then the Javascript in that file will be able to access the variables through phpvars. 只需将其放在包含whistle.js的上方,然后该文件中的Javascript就可以通过phpvars访问变量。 (Changing the variables.php file so that it has the same format as above, except no echoing of it). (更改variables.php文件,使其具有与上述相同的格式,但不回显该文件)。

To reiterate the previous feedback, PHP is used to generate HTML -- The PHP file itself is never available to the browser. 为了重申先前的反馈,PHP用于生成HTML-PHP文件本身永远不会对浏览器可用。 You can use the variables.php to generate hidden tags, then JavaScript to read them. 您可以使用variables.php生成隐藏标签,然后使用JavaScript读取它们。

eg, 例如,

variables.php output: variables.php输出:

<div id='varA' style='display:none'>foo</div>

javascript: javascript:

document.getElementById('varA').innerText

or 要么

variables.php output: variables.php输出:

  <input id='varB' type='hidden' value='bar' />

javascript: javascript:

 document.getElementById('varB').value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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