在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。

基本路径可以是以下示例中的任意一个:

http://www.example.com/
http://localhost/example
http://www.example.com/sub/example

例子也可能改变。


当前回答

格式为“hostname/pathname/search”

url是:

var url = window.location.hostname + window.location.pathname + window.location.hash

为了你的案子

window.location.hostname = "stackoverflow.com"
window.location.pathname ="/questions/25203124/how-to-get-base-url-with-jquery-or-javascript"
window.location.hash = ""

baseurl = hostname = window。location。hostname

其他回答

如果有人想把它分解成一个非常健壮的函数

    function getBaseURL() {
        var loc = window.location;
        var baseURL = loc.protocol + "//" + loc.hostname;
        if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
        // strip leading /
        var pathname = loc.pathname;
        if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
        var pathParts = pathname.split("/");
        if (pathParts.length > 0) {
            for (var i = 0; i < pathParts.length; i++) {
                if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
            }
        }
        return baseURL;
    }

你可以很容易地得到它:

var currentUrl = window.location.href;

或者,如果你想要原始的URL,使用:

var originalUrl = window.location.origin;

这是一个非常古老的问题,但以下是我个人使用的方法……

获取标准/基础URL

正如许多人已经指出的,这适用于大多数情况。

var url = window.location.origin;

获取绝对基础URL

但是,这种简单的方法可以用来去掉任何端口号。

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

编辑:为了解决Jason Rice提出的问题,可以使用以下方法自动插入正确的协议类型…

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

设置基础URL

还有一个好处——基URL可以全局重新定义。

document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";

我在几个Joomla项目中遇到过这种需求。我发现的最简单的方法是在模板中添加一个隐藏的输入字段:

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

当我需要的值在JavaScript:

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

不像使用纯JavaScript那样花哨,但很简单,可以完成工作。

这条会帮助你……

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];