相反,我會在模塊上公開一個方法來設置保存方法URL,然後調用該方法,而不是設置全局變量。
<script type="text/javascript">
window.onModuleLoaded = function(module)
{
module.setSaveMethodURL('<?php echo $this->getUrl("page/save") ?>');
}
</script>
然後,在你的模塊代碼,你會做類似如下的修改:(取決於設計模式你使用暴露你的模塊)
module = (function ($) {
var url = saveMethodUrl;
var setSaveMethodURL = function(save_url)
{
url = save_url;
return url;
}
var returnObject = {
setSaveMethodURL: setSaveMethodURL
};
//this is executed when the module is loaded via the <script> tag)
//check to see if the moduleLoaded callback is defined
if (typeof window.onModuleLoaded != undefined)
{
//if the moduleLoaded callback is defined and is a function, call it
if (typeof window.onModuleLoaded == 'function')
{
window.onModuleLoaded(returnObject);
}
//if it's defined and is an object, iterate through the object and call
//each function in the object. (this allows you to add multiple callbacks
//to be executed when this module is loaded
else if (typeof window.onModuleLoaded == 'object')
{
for (key in window.onModuleLoaded)
{
if (typeof window.onModuleLoaded[ key ] == 'function')
{
window.onModuleLoaded[ key ](returnObject);
}
}
}
}
//return a reference to your setSaveMethodURL api method
return returnObject;
})();
至於裝你的模塊異步,你可以看看這個其他stack overflow question about loading javascript asynchronously
Ajax不是這裏的一個選項。 – Sven
好的。那麼你的意思是你不喜歡將數據回顯到腳本標籤中? – iConnor
Ajax是建議方法的次選,因爲它會產生額外的網絡開銷。我傾向於說沒有更乾淨的方式。 –