how to get the base url in javascript

前端 未结 10 1821
一整个雨季
一整个雨季 2020-12-01 04:12

I am building a website with CodeIgniter, I have various resources that I load with the base_url helper function like this

相关标签:
10条回答
  • 2020-12-01 04:47

    One way is to use a script tag to import the variables you want to your views:

    <script type="text/javascript">
    window.base_url = <?php echo json_encode(base_url()); ?>;
    </script>
    

    Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript. I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it. With your given example:

    ...
    $('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");
    
    0 讨论(0)
  • 2020-12-01 04:49
    var baseTags = document.getElementsByTagName("base");
    var basePath = baseTags.length ? 
        baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
        "";
    
    0 讨论(0)
  • 2020-12-01 04:55

    This is done simply by doing this variable.

    var base_url = '<?php echo base_url();?>'
    

    This will have base url now. And now make a javascript function that will use this variable

    function base_url(string){
        return base_url + string;
    }
    

    And now this will always use the correct path.

    var path    =   "assets/css/themes/" + color_ + ".css"
    $('#style_color').attr("href", base_url(path) );
    
    0 讨论(0)
  • 2020-12-01 04:57

    To get exactly the same thing as base_url of codeigniter, you can do:

    var base_url = window.location.origin + '/' + window.location.pathname.split ('/') [1] + '/';
    

    this will be more useful if you work on pure Javascript file.

    0 讨论(0)
提交回复
热议问题