Kohana和Javascript路径

时间:2010-04-18 16:16:46

标签: javascript kohana

我有以下Kohana设置:

我的所有文件都放在'public_html / koh'下 我的js文件放在'public_html / koh / media / js /'

我使用html :: script helper来包含那些生成我跟随html代码的javascript文件:

<script type="text/javascript" src="/koh/media/js/site.js"></script>

在我的js中,我访问了一个像'json / getsomething'这样的控制器(http://localhost/koh/json/getsomething)。

只要我留在控制器的顶部,它就可以正常工作: http://localhost/koh/home

当我转到“http://localhost/koh/home/index”时,它会呈现相同的页面,但不再能从Javascript访问“json / getsomething”。

我该如何解决这个问题?

使用绝对路径包含Javascript? 在js中创建一个变量,如var fullPath ='http://localhost/koh/'?

这样做的最佳做法是什么?

Leonti

2 个答案:

答案 0 :(得分:4)

我就是这样做的。

我创建了一个函数url_base,它对应于kohana的url::base,因此当我从localhost移动到生产时它会转换。

查看模板:

<script type="text/javascript">
    function url_base() { return "<?php echo url::base();?>"; }
</script>

然后在config.php中:

if(IN_PRODUCTION) {
    $config['site_domain'] = '/';
}
else {
    //if in localhost redirect to localhost/mysite
    //instead of just localhost
    $config['site_domain'] = '/mysite/';
}

答案 1 :(得分:2)

(有点晚但希望仍然有用)这是我用来更好地组织我的js-serverside vars的另一种方式。

我把某些基本变量放在某处 - 例如。在“before()”函数中:

    $this->template->appconf = array(
        'url_base' => url::base(),
        'l' => substr(I18n::$lang, 0, 2),
    );

现在我可以在需要任何额外变量时添加:

    $this->template->appconf['page_key'] = 'product_page';

最后在模板中这个清洁:

<script type="text/javascript">
    var appconf = <?php echo json_encode($appconf); ?>;
</script>

像这样使用:

<script type="text/javascript">
    console.log(appconf.url_base); // "/mysite/"
</script>