你只能做最常用的方式,via parameter
你好.js
function jst(alertMe)
{
alert( alertMe );
}
索引.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsFileTest</title>
<script type="text/javascript" src="hello.js"></script>
<script type="text/javascript">
var alertMe = <?php echo 35; ?> ;
</script>
</head>
<body>
<button onclick="jst(alertMe)">Try it</button>
</body>
</html>
js
在你的php
文件中开发你的。
如果一切都按预期工作,那么您可以将所有内容外包为单独的文件.js
但请记住:php 在服务器端进行解析和解释。所以外面的一切都php tags
被完全忽略了。所以 :
<script type="text/javascript" src="jsFile.js"></script>
是纯html,将被忽略。服务器端php
对这些文件的存在一无所知.js
,它不会加载和解析它。但如果您php
也想解释这个文件,这是必需的。
如果你想将它包含在一个php
文件中,你可以这样做
放在<script type="text/javascript">
开头。代码完成再次开始。
js文件.php

index2.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsFileTest</title>
<?php
include_once 'jsFile.php';
?>
</head>
<body>
<?php
echo "myID = ".$myId."<br>";
?>
<button onclick="myFunction()">Try it</button>
</body>
</html>
跑步 :

但现在我们来到了重要的部分。
查看 html 输出源:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsFileTest</title>
<script type="text/javascript">
function myFunction()
{
alert("Hi from jsFile.php");
}
</script>
</head>
<body>
myID = idontknow<br>
<button onclick="myFunction()">Try it</button>
</body>
</html>
如您所见,javascript( function myFuntion()
) 直接插入到 html 输出中。这正是不会发生的事情
<title>jsFileTest</title>
<script type="text/javascript" src="jsFile.js"></script>
你不能使用src="jsFile.php"
<script type="text/javascript" src="jsFile.php"></script>
解析完成后,内容被发送到客户端。从这一刻起,甚至尝试在 javascript 中解析嵌入的 php 代码也没有用。(服务器不再参与,已经完成了它的工作)
IE 检测到错误(状态行)。当你双击这个

弹出错误窗口

浏览器需要有效的 javascript 代码,而这
$myId = "idontknow";
不是有效的 JS 代码。