在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。
其他回答
这里有一些也适用于file:// url的快速方法。
我想出了这样一句话:
[((1!=location.href.split(location.href.split("/").pop())[0].length?location.href.split(location.href.split("/").pop())[0]:(location.protocol,location.protocol+"//" + location.host+"/"))).replace(location.protocol+"//"+location.protocol+"//"+location.protocol+"://")]
如果有人想把它分解成一个非常健壮的函数
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;
}
文档。baseURI返回的基本URL也与<base/>标签中的值有关 https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI
这在javascript中是不可能的,因为这是一个服务器端属性。客户端上的Javascript无法知道joomla安装在哪里。最好的选择是在页面javascript中包含$this->baseurl的值,然后使用这个值(phpBaseUrl)。
然后你可以像这样构建url:
var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;
你可以很容易地得到它:
var currentUrl = window.location.href;
或者,如果你想要原始的URL,使用:
var originalUrl = window.location.origin;