3
  • 我正在开发一个 javascript 模块,它为复杂的页面添加了很多功能。
  • 数据绑定是用 php 完成的。
  • 根据 html5boilerplate 的建议,我将 js 文件放在页面末尾

如何将数据从服务器传递到我的 js 模块?我唯一能想到的是:将数据存储在某个 DOM 变量中,然后从 JS 文件中读取它。像这样:

PHP:

 <script type="text/javascript">
     var saveMethodUrl = '<?php echo $this->getUrl("page/save") ?>';
 </script>

JS:

module = (function ($) {
   var url = saveMethodUrl;
   ...

但这似乎有点肮脏。有没有关于如何做到这一点的最佳实践?

4

2 回答 2

1

相反,我会在您的模块上公开一个方法来设置保存方法 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;

})();

至于异步加载您的模块,您可以查看有关异步加载 javascript 的其他堆栈溢出问题

于 2013-07-09T12:44:46.180 回答
1

如何调用返回 Javascript 文件的 PHP 脚本:

<script src="my_js_variables.php"></script>

在你的my_js_variables.php你有:

<?php

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

$variables = array('saveMethodUrl' => $this->getUrl("page/save"));

echo "var php = " . json_encode($variables);

?>

您可以访问 JS 文件中的变量,例如php.saveMethodUrl.

这实际上与您提出的解决方案没有任何不同,但我认为它更清洁。

于 2013-07-09T12:58:13.380 回答