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

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

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

例子也可能改变。


当前回答

window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"

几乎和Jenish的答案一样,但更短一点。

其他回答

这里有一些也适用于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+"://")]
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

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

获取标准/基础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 + "' />";

您提到example.com可能会更改,因此我怀疑实际上您需要基本url,以便能够为脚本使用相对路径表示法。在这种特殊情况下,不需要使用脚本-而是添加base标签到你的头:

<head>
  <base href="http://www.example.com/">
</head>

我通常通过PHP生成链接。

获取基本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;
}
  }
}