我有一个PHP文件,我想从它传递一个参数到JavaScript文件,这看起来很简单,但我就是不能执行它,我的方式不起作用,我不知道为什么!!
这两个文件的代码加上另一个用于查看结果的HTML代码,,`
php文件..
<?php
$ser = "server";
?>
<script type="text/javascript">var server = "<?= $ser ?>";</script>
<script type="text/javascript" src="new4.js"></script>new4.js ( Java脚本文件)
function myFunction() {
alert("server: " + server);
}这是用来查看结果的HTML文件
<!DOCTYPE html>
<html>
<body>
<script src="new4.js"></script>
<p>Click the button to demonstrate line-breaks in a popup box.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>发布于 2016-06-14 00:27:07
您将无法访问第二个JavaScript文件中的server JavaScript变量,除非您在此文件中实际声明了该变量,或者以某种方式包含了该声明。
<!DOCTYPE html>
<html>
<body>
<?php
$ser = "server";
?>
<script type="text/javascript">var server = "<?= $ser ?>";</script>
<script src="new4.js"></script>
<p>Click the button to demonstrate line-breaks in a popup box.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>(new4.js不需要更改)。
PS:您可能需要将文件重命名为PHP,或者确保您的You服务器将HTML解析为PHP。
另一种方法(我自己还没有尝试过,但应该可以用)。
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src='constants.php'></script>
<script src="new4.js"></script>
<p>Click the button to demonstrate line-breaks in a popup box.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>constants.php
<?php
header('Content-Type: text/javascript');
$ser = "server";
echo "server = \"$ser\"";https://stackoverflow.com/questions/37794580
复制相似问题