在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
例子也可能改变。
当前回答
我很惊讶,如果在<base>标签中设置,那么没有答案考虑基url。当前的所有答案都试图获取主机名或服务器名或地址的第一部分。这是完整的逻辑,它也考虑了<base>标记(它可能指的是另一个域或协议):
function getBaseURL(){
var elem=document.getElementsByTagName("base")[0];
if (typeof(elem) != 'undefined' && elem != null){
return elem.href;
}
return window.location.origin;
}
Jquery格式:
function getBaseURL(){
if ($("base").length){
return $("base").attr("href");
}
return window.location.origin;
}
在不涉及上述逻辑的情况下,同时考虑<base>标记和window.location.origin的简写解决方案:
Js:
var a=document.createElement("a");
a.href=".";
var baseURL= a.href;
Jquery:
var baseURL= $('<a href=".">')[0].href
最后注意:对于您计算机中的本地文件(不是主机上的),window.location.origin只返回文件://,但上面的分类方法返回完整的正确路径。
其他回答
最简单的方法,以JavaScript获得基础url
window.location.origin
这里有一些也适用于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+"://")]
获取基本url 从js调用控制器
function getURL() {
var windowurl = window.location.href;
var baseUrl = windowurl.split('://')[1].split('/')[0]; //split function
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/url from controller';
xhr.open("GET", url);
xhr.send(); //object use to send
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && this.status==200){
//console.log(xhr.responseText); //the response of the request
document.getElementById("id from where you called the function").innerHTML = xhr.responseText;
}
}
}
你可以很容易地得到它:
var currentUrl = window.location.href;
或者,如果你想要原始的URL,使用:
var originalUrl = window.location.origin;
这在javascript中是不可能的,因为这是一个服务器端属性。客户端上的Javascript无法知道joomla安装在哪里。最好的选择是在页面javascript中包含$this->baseurl的值,然后使用这个值(phpBaseUrl)。
然后你可以像这样构建url:
var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;