Javascript 从外部javascript文件访问PHP var
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2928827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access PHP var from external javascript file
提问by FFish
I can access a PHP var with Javascript like this:
我可以像这样使用 Javascript 访问 PHP var:
<?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:
但是如果我想使用外部 JS 文件怎么办:
<script type="text/javascript" src="externaljs.js"></script>
externaljs.js:
外部js.js:
alert("color: " + "<?php echo $color; ?>");
回答by Don
You don't really access it, you insert it into the javascript code when you serve the page.
您并没有真正访问它,而是在提供页面时将其插入到 javascript 代码中。
However if your other javascript isn't from an external source you can do something like:
但是,如果您的其他 javascript 不是来自外部来源,您可以执行以下操作:
<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>
and then in the file.js use color like so:
然后在 file.js 中使用如下颜色:
alert("color: " + color);
回答by Atanas Kovachev
You can also access data from php script in Javascript (I'll use jQuery here) like this
您还可以像这样从 Javascript 中的 php 脚本访问数据(我将在这里使用 jQuery)
Create input hidden field within you php file like this
像这样在你的 php 文件中创建输入隐藏字段
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
在您的 javascript 文件中:
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 :)
这也将完成这项工作:)
回答by ólafur Waage
What I've seen done is let .js files run through the php interpreter. Which I can not recommend.
我所看到的是让 .js 文件通过 php 解释器运行。我不能推荐。
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.
我推荐的是通过 AJAX 获取值并让 PHP 文件将值返回给 JS 文件。这是一种更清洁的方法。
回答by Your Common Sense
First of all you have to understand that no program can actually have access to the other program's variable.
首先,您必须了解没有程序实际上可以访问其他程序的变量。
When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well
当你意识到这一点时,剩下的就很简单了。
您可以在主文件中设置一个 js 变量,然后包含您的外部 js,或者使这个外部 js 动态化,也可以由 PHP 生成
回答by TerryP
What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa
您可能想要的称为异步 JavaScript 和 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.
基本上,想象一下能够将消息从客户端 JavaScript 发送到服务器上的 PHP 脚本。在您提供的示例 (externaljs.js) 中,您可以让脚本通过 HTTP 询问服务器 $color 是什么。您还可以将脚本标记指向生成所需 JavaScript 的 PHP 脚本。这取决于您需要做什么。
It helps to have some understanding of taint checking, data verification, and security ;)
它有助于对污点检查、数据验证和安全性有一些了解;)
回答by dnagirl
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.
正如其他人所说,javascript 无法访问 php 变量。但是,它确实可以访问 DOM。因此,您可以使用 php 向某些页面元素添加属性。然后您可以使用 javascript 访问这些属性。
e.g. <div id='apple' class='red'>is completely available to javascript
eg<div id='apple' class='red'>对 javascript 完全可用
回答by Mr Rubix
Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:
Don 解决方案很好,此外,如果您想在外部 javascipt 中使用 php 数组,这可以帮助您:
PHP:
PHP:
<?php
$my_php_array = [];
?>
HTML:
HTML:
<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>
Javasript: (You can now use the array like a normal Javascript array)
Javasript:(您现在可以像使用普通的 Javascript 数组一样使用该数组)
my_js_array[0]
my_js_array.length
回答by AlexioVay
2017-2018 and above solution:
2017-2018及以上解决方案:
Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encodeand json_encodeyet, you could even send PHP Array variables like that:
由于没有人bringed它,但我猜相结合的功能谁也没想到base64_encode和json_encode的是,你甚至可以发送PHP数组变量这样的:
index.php
索引.php
<?php
$string = "hello";
$array = ['hi', 'how', 'are', 'you'];
$array = base64_encode(json_encode($array));
Then you could just load your desired js file with the parameter for a query string like this:
然后,您可以使用查询字符串的参数加载所需的 js 文件,如下所示:
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
Then js/main.phpwill look like this for example. You can test your variables this way:
js/main.php例如,然后看起来像这样。您可以通过以下方式测试变量:
js/main.php
js/main.php
<?php
if ($_GET['string']) {
$a = $_GET['string'];
}
if ($_GET['array']) {
$b = $_GET['array'];
}
$b = json_decode(base64_decode($b));
echo 'alert("String $a: + '.$a.'");';
echo 'alert("First key of Array $array: + '.$b[0].'");';
exit();
?>
The following will then output when you open your index.php. So you see, you don't open js/main.phpand you still got the javascript functionality from it.
当您打开index.php. 所以你看,你没有打开js/main.php,你仍然可以从中获得 javascript 功能。
回答by Serty Oan
<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 脚本可以像这样编写 JavaScript:
<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...
Though using AJAX like said Sepehr Lajevardi would be much cleaner
虽然像Sepehr Lajevardi所说的那样使用AJAX会更干净
回答by Manos Dilaverakis
externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.
externaljs.js 是一个静态文件。当然它不能访问PHP数据。将 PHP 数据传递给 js 文件的唯一方法是通过在 PHP 脚本中写入文件来物理更改文件,尽管这充其量只是一个混乱的解决方案。
Edit in response to ólafur Waage's answer: I guess writing to the js file isn't the onlyway. Passing the js through the PHP interpreter never crossed my mind (for good reason).
针对 ólafur Waage 的回答进行编辑:我想写入 js 文件不是唯一的方法。我从未想过通过 PHP 解释器传递 js(有充分的理由)。


