在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。
基本路径可以是以下示例中的任意一个:
http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
例子也可能改变。
在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。
基本路径可以是以下示例中的任意一个:
http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
例子也可能改变。
当前回答
我建议每个人在开发中创建HTML基础标签,然后动态分配href,所以在生产中,无论客户端使用什么主机,它都会自动适应它:
<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>
...
因此,如果您在localhot:8080中,您将从基中访问每个链接或引用的文件,例如:http://localhost:8080/some/path/file.html 如果你在www.example.com,它将是http://www.example.com/some/path/file.html
还要注意的是,你所在的每个位置,你不应该在hrefs中使用像glob这样的引用,例如:父位置导致http://localhost:8080/而不是http://localhost:8080/some/path/。
假装你引用所有的超链接作为完整的句子没有bas url。
其他回答
这条会帮助你……
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
这是一个简短的例子:
const base = new URL('/', location.href).href; console.log(基地);
我认为这对你很有用:
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );
这是一个非常古老的问题,但以下是我个人使用的方法……
获取标准/基础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 + "' />";