简体   繁体   中英

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?

<?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:

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

And on the JS end, you would want to do:

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

And var1 and var2 would be 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. (Changing the variables.php file so that it has the same format as above, except no echoing of it).

To reiterate the previous feedback, PHP is used to generate HTML -- The PHP file itself is never available to the browser. You can use the variables.php to generate hidden tags, then JavaScript to read them.

eg,

variables.php output:

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

javascript:

document.getElementById('varA').innerText

or

variables.php output:

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

javascript:

 document.getElementById('varB').value

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