开发者

Kohana and Javascript path

I have a following Kohana setup:

All my files are placed under 'public_html/koh' My js files are placed under 'public_html/koh/media/js/'

I use html::script helper to include those javascript files which generates me following html code:

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

In my js I access one of controllers like 'json/getsomething' (which is http://localhost/koh/json/getsomething).

It works OK as long as I'm staying in top of the controller: http://localhost/koh/home

When I go to 'http://localhost/koh/home/index' it renders the same page of course but 'json/getsomething' is not accessible from Javascript anymore.

How can I solve this problem?

In开发者_StackOverflowclude Javascript using absolute path? Create a variable in js like var fullPath = 'http://localhost/koh/'?

What is the best practice to do it?

Leonti


That's how I did it.

I made a function url_base which would correspond to kohana's url::base and so it would switch around when I moved from localhost and to production.

View template:

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

And then in config.php:

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


(A bit late but hope still useful) Here's another way I use to better organize my js-serverside vars.

I put somewhere in beginning some basic variables - eg. in "before()" function:

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

Now I can add whenever I need any extra variable:

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

And finally in template this cleaniness:

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

Use like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜