PHP - 生成JavaScript [英] PHP - generating JavaScript
问题描述
我正在开发一个包含大量JavaScript的项目。我认为生成简单的字符串并将它们放在< script>之间标签不是最好的方法。
I am working on a project which has a lot of JavaScript. I think that generating simple strings and putting them between "<script>" tags is not the best way to do it.
有没有更好的方法来生成JavaScript对象,函数,调用等?也许有些融合类(从PHP到JavaScript)或者我应该遵循哪些设计模式?
Are there any better approaches to generate JavaScript objects, functions, calls etc? Maybe some convering classes (from PHP to JavaScript) or maybe there are design patterns I should follow?
PS。如果它有任何相关性 - 我使用MooTools和MochaUI(使用MochaPHPControl)。
PS. If it has any relevance - I am using MooTools with MochaUI (with MochaPHPControl).
预先感谢您的帮助。
推荐答案
最好的方法是将Javascript视为PHP代码。
The best approach is to think Javascript as PHP code.
基本步骤是:
- 创建一个.htaccess文件,将所有JS文件(.js)重定向到索引文件。
- 在此索引中文件加载JS文件作为PHP模块(
requirescript / $ file
) - 根据需要修改所有JS文件。现在你可以嵌入PHP代码了。
例如,在你的.htaccess这一行添加:
For instance, add to your .htaccess this line:
RewriteRule \.js$ index.php
在你的index.php文件中输入之类的内容:
In your index.php file put something like this:
// Process special JS files
$requested = empty($_SERVER['REQUEST_URI']) ? "" : $_SERVER['REQUEST_URI'];
$filename = get_filename($requested);
if (file_ends_with($requested, '.js')) {
require("www/script/$filename.php");
exit;
}
最后在你的file.js.php中你可以嵌入PHP,使用GET和POST参数等:
And finally in your file.js.php you can embed PHP, use GET and POST params, etc:
<?php header("Content-type: application/x-javascript"); ?>
var url = "<?php echo $url ?>";
var params = "<?php echo $params ?>";
function xxxx()....
....
此外,跳过文件缓存的技巧是将随机数添加为javascript参数:
In addition, a trick to skip file cache is to add a random number as javascript parameter:
<script type="text/javascript" src="scripts/file.js?a=<?php echo rand() ?>"></script>
此外,如评论中所述,如果您的网络服务器不允许修改 .htaccess
,你可以直接询问PHP文件:
Also, as said in a comment, if your webserver don't allow to modify the .htaccess
, you can just ask for the PHP file directly:
<script type="text/javascript" src="file.php"></script>
这篇关于PHP - 生成JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!