Mic*_*yen 16
如果将PHP解释器配置为在*.js文件上运行,您将只能执行此操作,默认情况下不会这样做.老实说,我不推荐这种行为.
我要做的是这样的事情(这个方法也可以用于CSS文件.):
<script type="text/javascript" src="js.php"></script>
Run Code Online (Sandbox Code Playgroud)
js.php
<?php
//GZIP the file and set the JavaScript header
ob_start("ob_gzhandler");
header("Content-type: text/javascript");
//Set a JavaScript variable based on PHP work
echo 'var logged_in_user = "'.$_SESSION['username'].'";';
//Require an external script
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/jquery.js");
?>
//More Javascript functions and code here
$(document).ready(function() {
$('#mydiv').tipsy();
});
<?php
//Flush the output buffer
ob_end_flush();
?>
Run Code Online (Sandbox Code Playgroud)
我个人这样做有很多原因.
它是添加,删除或修改整个站点的JavaScript的中心位置.我甚$_GET至可以使用检查来根据我编写<script>标记的方式使某些脚本成为条件.
例如,<script type="text/javascript" src="js.php?var=1"></script>.然后我可以$_GET['var']在js.php文件中查看.