How to get base url with jquery or javascript?

后端 未结 24 1267
忘掉有多难
忘掉有多难 2020-12-12 13:59

In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the follo

相关标签:
24条回答
  • 2020-12-12 14:40

    the easiest way to get base url in jQuery

    window.location.origin
    
    0 讨论(0)
  • 2020-12-12 14:41

    I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:

    <input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />
    

    When I need the value in JavaScript:

    var baseurl = document.getElementById('baseurl').value;
    

    Not as fancy as using pure JavaScript but simple and gets the job done.

    0 讨论(0)
  • 2020-12-12 14:42

    Put this in your header, so it will be available whenever you need it.

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

    You will get http://localhost:81/your-path-file or http://localhost/your-path-file.

    0 讨论(0)
  • 2020-12-12 14:43

    Here's a short one:

    const base = new URL('/', location.href).href;
    
    console.log(base);

    0 讨论(0)
  • 2020-12-12 14:45

    I would recommend for everyone to create HTML base tag in development, then assign the href dynamically, so in production whatever host a client uses, it will automacically addapt to it:

    <html>
     <title>Some page title</titile>
      <script type="text/javascript">
        var head  = document.getElementsByTagName('head')[0];
        var base = document.createElement("base");
        base.href = window.document.location.origin;
        head.appendChild(base);
      </script>
     </head>
     ...
    

    So if you are in localhot:8080, you will reach every linked or referenced file from the base, eg: http://localhost:8080/some/path/file.html If you are in www.example.com, it will be http://www.example.com/some/path/file.html

    Also note that, every location you're on, you should not use references like globs in hrefs, eg: Parent location causes http://localhost:8080/ not http://localhost:8080/some/path/.

    Pretent you reference all hyperlinks as full sentenced without the bas url.

    0 讨论(0)
  • 2020-12-12 14:47

    I think it will ok for you

    var base_url = window.location.origin;
    
    var host = window.location.host;
    
    var pathArray = window.location.pathname.split( '/' );
    
    0 讨论(0)
提交回复
热议问题