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

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

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

例子也可能改变。


当前回答

更简单的答案在这里,window。location。href = window。location。origin;

其他回答

拆分并加入URL:

const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))

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

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

我通常通过PHP生成链接。

文档。baseURI返回的基本URL也与<base/>标签中的值有关 https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI

最简单的方法,以JavaScript获得基础url

window.location.origin

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