PHP/APACHE : can i auto_prepend to a . js 文件?

标签 php javascript apache .htaccess

我想使用 auto_prepend_file 我的所有 js 文件:

var SITE_ROOT = 'http://www.mydomain.com';

可以像处理 php 文件一样在 .htaccess 中完成此操作吗?如果可以,怎么做?!!!

最佳答案

您可以使用 mod_rewrite 规则和一个小的 php 文件来完成您正在寻找的内容:

js_wrapper.php:

<?php
// Open a javascript file provided by ?file=somefile.js and to prepend some content

$file = $_GET['file'];

// Checks that the file exists on the system and that it ends in '.js'
// The RewriteCond's do the same thing, but this prevents direct 
// calls to js_wrapper.php as well
if(!is_file("./" . $file) OR !preg_match('#\.js$#', $file)) {
    // 404
    header("HTTP/1.0 404 Not Found");
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
<html><head> 
<title>404 Not Found</title> 
</head><body> 
<h1>Not Found</h1> 
<p>The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found on this server.</p> 
<hr> 
</body></html>';

}

header("Content-type: text/javascript");

// Begin prepended content
?>
// Auto-prepended by js_wrapper
var SITE_ROOT = 'http://www.mydomain.com';
// End auto-prepend

<?php 
// Output the original file
echo file_get_contents($file);
?>

.htaccess:

# Pass all requests to js/some/script.js through js_wrapper.php?file=js/some/script.js
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} \.js$
RewriteRule ^js/(.*)$  js_wrapper.php?file=js/$1  [L,NC,QSA]

如果您的脚本不在名为“js”的文件夹下,您应该修改 RewriteRule 指令以反射(reflect)不同的路径。

或者...

由于在您的示例中,您只是在开始时定义一个变量,如果这就是您想要做的,那么您应该能够通过使用 <script> 来完成此操作阻止您的 <head>页面 block ,包括 js 脚本。 js 脚本将能够访问您在那里定义的任何变量。这更简单,更容易维护,使用更少的“魔法”(阅读渲染的 html 源代码和 js 的人不会理解前置数据来自哪里,除非他们阅读 .htaccess),这就是我可能会做的事情正在努力实现。

<head>
... stuff ...
    <script type="text/javascript">
        var SITE_ROOT = 'http://www.example.com';
    </script>
    <script type="text/javascript" src="/js/some_script.js"></script> 
    <script type="text/javascript" src="/js/some_other_script.js"></script> 
... stuff ...
</head>

关于PHP/APACHE : can i auto_prepend to a . js 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3438726/

相关文章:

javascript - Raphael 2 - 鼠标按下时画线

JavaScript - 缺失;声明之前

php - 变量中无法识别下划线和破折号

javascript - 使用 PHP 的 MySQL 查询未返回预期数据

php - 在 php 中从 mysql 按表显示组

php - 如何快速执行多个mysql查询

javascript - 如何从 android -Cordova/Phonegap 调用 javascript 函数

php - 如果表2在某些条件下包含相同的值,则从表1中删除行 mysql

mysql - 尽管新连接在负载下失败,但似乎无法达到 MySQL max_connections

ruby-on-rails - 未写入日志文件(乘客)