How to get base url with jquery or javascript?

后端 未结 24 1450
忘掉有多难
忘掉有多难 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:55

    This is an extremely old question, but here are the approaches I personally use ...

    Get Standard/Base URL

    As many have already stated, this works for most situations.

    var url = window.location.origin;
    


    Get Absolute Base URL

    However, this simple approach can be used to strip off any port numbers.

    var url = "http://" + location.host.split(":")[0];
    

    Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...

    var url = window.location.protocol + "//" + location.host.split(":")[0];
    


    Set Base URL

    As a bonus -- the base URL can then be redefined globally.

    document.head.innerHTML = document.head.innerHTML + "";
    

提交回复
热议问题