在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只返回文件://,但上面的分类方法返回完整的正确路径。

其他回答

这条会帮助你……

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( '/' );

容易

$('<img src=>')[0].src

生成一个带有空src-name的img会迫使浏览器自己计算base-url,不管你是否有/index.html或其他什么。

把它放在你的标题中,这样当你需要它的时候就可以使用了。

var base_url = "<?php echo base_url();?>";

您将得到http://localhost:81/your-path-file或http://localhost/your-path-file。