将您的Javascript放在.php文件中有什么好处? [英] What are the advantages to putting your Javascript in a .php file?
问题描述
我偶尔会遇到通过PHP文件包含一些Javascript的页面:
I occasionally come across pages where some Javascript is included via a PHP file:
<html>
<head>
<script type="text/javascript" src="fake_js.php"></script>
</head>
<body onload="handleLoad();">
</body>
</html>
其中 fake_js.php 的内容可能如下所示:
where the contents of fake_js.php might look something like this:
<?php header('Content-type: text/javascript') ?>
function handleLoad() {
alert('I loaded');
}
包含这样的Javascript有哪些优点(或缺点)?
What are the advantages (or disadvantages) to including Javascript like this?
推荐答案
它可以很容易地从服务器端设置javascript变量。
It makes it easy to set javascript variables from the server side.
var foo = <?=$foo?>
我的项目中通常有一个php / javascript文件,我用它来定义需要的任何变量用于javascript。这样我就可以在javascript中轻松访问服务器端使用的常量(css颜色,非敏感网站属性等)。
I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.
编辑:例如,这是我正在处理的项目中的 config.js.php
文件的副本。
For example here's a copy of my config.js.php
file from the project I'm currently working on.
<?php
require_once "libs/config.php";
if (!function_exists("json_encode")) {
require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";
?>
这篇关于将您的Javascript放在.php文件中有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!