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

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

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

例子也可能改变。


当前回答

这在javascript中是不可能的,因为这是一个服务器端属性。客户端上的Javascript无法知道joomla安装在哪里。最好的选择是在页面javascript中包含$this->baseurl的值,然后使用这个值(phpBaseUrl)。

然后你可以像这样构建url:

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;

其他回答

格式为“hostname/pathname/search”

url是:

var url = window.location.hostname + window.location.pathname + window.location.hash

为了你的案子

window.location.hostname = "stackoverflow.com"
window.location.pathname ="/questions/25203124/how-to-get-base-url-with-jquery-or-javascript"
window.location.hash = ""

baseurl = hostname = window。location。hostname

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

我建议每个人在开发中创建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。

我在几个Joomla项目中遇到过这种需求。我发现的最简单的方法是在模板中添加一个隐藏的输入字段:

<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />

当我需要的值在JavaScript:

var baseurl = document.getElementById('baseurl').value;

不像使用纯JavaScript那样花哨,但很简单,可以完成工作。

这在javascript中是不可能的,因为这是一个服务器端属性。客户端上的Javascript无法知道joomla安装在哪里。最好的选择是在页面javascript中包含$this->baseurl的值,然后使用这个值(phpBaseUrl)。

然后你可以像这样构建url:

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;