我在用户的网站上有一行代码,它从我的服务器请求脚本:
<script src="myserver.com/getjs?user=1"></script>
php提供js,在代码中插入用户的id:
(function(){
var userid = 1; //written out from $_GET['user']
...js code...
})();
现在,我想根据用户的id输出不同的js。我不想有很多不同的js文件,而是想有一种方法来"模块化"基于我在数据库中的用户设置发送的代码,这样用户就不需要更改网站上的代码。我能看到的唯一方法是输出这样的js文件:
...first PHP will get some user settings from the db based on their userid...
...then the js is output...
(function(){
var userid = 1; //written out from $_GET['user']
<?php if( $userOption1 ){ ?>
function _option1(userid){ //func required if option1 true
...func1 code...
}
_option1(userid); //ruin it in js
<?php } ?>
<?php if( $userOption2 ){ ?>
function _option2(userid){ //func required if option2 true
...func2 code...
}
_option2(userid); //run it in js
<?php } ?>
...and so on...
})();
但我相信必须有一种更有效的方法来管理这件事。这样做的部分原因是为了让每个用户的代码尽可能小,但主要是因为我正在构建一些用户不想要的功能——它需要对每个人都是动态的。
感谢任何能提供帮助的人!
您可以使用Require.JS(网站)。它根据需要异步加载脚本。要加载库,您可以使用:
<script data-main="js/loadScripts.php" src="libs/require.js"></script>
它基本上告诉Require.JS在加载完成后运行"loadScripts.php"javascript文件(是的,loadScripts.hp需要返回javascript,在那里你可以为任何用户返回自定义库)。
在loadScripts.php中,您可以执行以下操作:
<?php
// Generate en array of loading scripts, you'll probably want to dynamically
// generate this array according to user access permissions or any other case
$scriptsToLoad = array("script1", "script2", "script3");
$loadingList = "[";
$argumentsList = "";
foreach ($scriptsToLoad AS $script)
{
$loadingList .= "'"{$script}'", ";
$argumentsList .= "{$script}, ";
}
$loadingList = substr($loadingList, 0, strlen($loadingList) - 2);
$loadingList .= "]";
$argumentsList = substr($argumentsList, 0, strlen($argumentsList - 2);
echo "require({$loadingList}, function({$argumentsList}) {});'n";
?>
我还没有测试过,但你可以在它的网站上找到一个想法。请注意,脚本的调用不带".js",并且需要在loadScripts的同一文件夹中(它们可以在子文件夹中,像subfoldername/scriptName
一样调用以加载文件js/subfoldername/scriptName.js
)。
argumentsList将定义包含加载模块的变量。模块的定义如下:
$(function() {
// Stuff...
var module = {
doSomething: function() {
// .......
},
anyValueYouWant: 5
};
return module;
});
当然,有很多方法可以定义模块,您需要阅读API文档。希望这能有所帮助。