Access PHP var from external javascript file

2020-01-23 11:33发布

I can access a PHP var with Javascript like this:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>

But what if I want to use an external JS file:

<script type="text/javascript" src="externaljs.js"></script>

externaljs.js:

alert("color: " + "<?php echo $color; ?>");

12条回答
2楼-- · 2020-01-23 12:06

You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js

查看更多
在下西门庆
3楼-- · 2020-01-23 12:12

As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.

e.g. <div id='apple' class='red'> is completely available to javascript

查看更多
ら.Afraid
4楼-- · 2020-01-23 12:13

What I've seen done is let .js files run through the php interpreter. Which I can not recommend.

What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.

查看更多
倾城 Initia
5楼-- · 2020-01-23 12:13

What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa

Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.

It helps to have some understanding of taint checking, data verification, and security ;)

查看更多
做自己的国王
6楼-- · 2020-01-23 12:14
<script type="text/javascript" src="externaljs.js"></script>

You could change it to

<script type="text/javascript" src="externaljs.php"></script>

And the PHP script could just write JavaScript like that :

<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...

Though using AJAX like said Sepehr Lajevardi would be much cleaner

查看更多
霸刀☆藐视天下
7楼-- · 2020-01-23 12:17

You can also access data from php script in Javascript (I'll use jQuery here) like this

Create input hidden field within you php file like this

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />

in your javascript file:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

This will do the job as well :)

查看更多
登录 后发表回答