如何使用jquery或javascript获取基本URL?


152

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

基本路径可以是以下任何示例:

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

example也可能改变。



@Mritunjay我已经看到了,但是在我的情况下,基本路径是不同的,因为我希望像在joomla中一样获得php中的基本路径
Navin Rauniyar 2014年

因此,没有答案能解决您的问题吗?
Artjom B.

选择答案,好吗?
allanberry

Answers:


177

这将帮助您...

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

是的,它有效!http://localhost/myapp/what/ever/sub/folder-> getBaseUrl-> http://localhost/myapp:-)
vee

3
这并非在所有情况下都有效,如@Artjom B以某种方式对问题的解答所指出的那样。例如,当通过本地网络测试站点(并且用IP +本地路径替换域)时,基本url可能类似于192.168.0.23/~sites/site/html/代替site.dev。也不能选择使用Javascript获取完整的路径名,因为站点可以具有任意数量的虚拟子目录。
肯定

124

我觉得你会没事的

var base_url = window.location.origin;

var host = window.location.host;

var pathArray = window.location.pathname.split( '/' );

7
不错,简短而甜蜜,谢谢。window.location.origin
TetraDev

1
这应该是首选答案,因为它简短,简洁并且可以正常工作。
格雷戈尔

window.location.origin未在ie9中定义
-jnoreiga

1
@jnoreiga谁还在使用ie9ツ
Alexandre Daubricourt

2
我希望它就是这么简单@AlexandreDaubricourt
jnoreiga

30

这将获得基本URL

var baseurl = window.location.origin+window.location.pathname;

这与window.location.href
Z. Khullah '16

8
这是不一样的,路径名为您提供了url的路径段,href也包含了查询参数
dschulten

24

这是一个非常老的问题,但这是我个人使用的方法...

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

1
除非您的协议不是HTTP之类的HTTP,例如https(然后将url协议设置为“ http://”,这会根据您如何使用url出现一些非常奇怪的错误)。
詹森·赖斯

13

使用javascript不可能,因为这是服务器端属性。客户端上的Javascript无法知道joomla的安装位置。最好的选择是以某种方式将$this->baseurljavascript 的值包含到页面javascript中,然后使用此值(phpBaseUrl)。

然后,您可以像这样构建网址:

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

1
请注意,loc.host该端口具有端口号,对于http://localhost:8082/这种方法将产生的网址http://localhost:8082:8082/window.location.hostname应改为使用。
Tiberiu C.

@TiberiuC。谢谢,补充。
Artjom B.


8

前段时间有同样的问题,我的问题是,我只需要基本URL。这里有很多详细的选项,但是要解决这个问题,只需使用window.location对象。实际上是在浏览器控制台中键入此内容,然后按Enter键以在那里选择您的选项。对我来说,这很简单:

window.location.origin

7
var getUrl = window.location;
var baseurl = getUrl.origin; //or
var baseurl =  getUrl.origin + '/' +getUrl.pathname.split('/')[1]; 

但是您不能说CodeIgniter(或php joomla)的baseurl()将返回相同的值,因为可以在这些框架的.htaccess文件中更改baseurl。

例如 :

如果您的本地主机中有一个.htaccess文件,例如:

RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

$ this-> baseurl()将返回http:// localhost / CodeIgniter /


6

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

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

当我需要JavaScript中的值时:

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

不像使用纯JavaScript那样花哨,而是简单并且可以完成工作。



3

我建议所有人在开发中创建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中使用globs之类的引用,例如:父级位置导致http://localhost:8080/not http://localhost:8080/some/path/

伪装您将所有超链接引用为完整的句子,没有bas url。


3

格式为主机名/路径名/搜索

因此,网址为:

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


3

令我惊讶的是,如果没有在<base>标签中设置基本网址,那么所有答案都不会考虑它。当前所有答案都尝试获取主机名或服务器名或地址的第一部分。这是完整的逻辑,还考虑了<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仅返回,file://但是上面的排序解决方案返回完整的正确路径。


1
这不是最好的方法。另外,请参阅@DaniilSamoylov的答案,该答案的确包含了<base>元素。
布拉德,

baseURI返回节点的基本URL,因此在这种情况下,它返回基本路径+文档名称。您将需要更多代码才能从该URL中删除文档名称。@Brad
Ali Sheikhpour

该解决方案并不能在网页的根目录是一个子目录(如内给予回复正确的基础URL example.com/appRoot)。仅当网页的根目录直接位于虚拟主机的根目录上时,它才起作用。
迈克尔·哈夫纳

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

几乎与Jenish答案相同,但略短一些。


2

我正处于同一阶段,此解决方案对我有用

在视图中

<?php
    $document = JFactory::getDocument();

    $document->addScriptDeclaration('var base = \''.JURI::base().'\'');
    $document->addScript('components/com_name/js/filter.js');
?>

在js文件中,您可以base在场景中将其作为变量进行访问:

console.log(base) // will print
// http://www.example.com/
// http://localhost/example
// http://www.example.com/sub/example

我不记得我在何处获取此信息以功劳,如果找到它,我将编辑答案


1
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

1
请考虑在您的答案中添加说明。
摩羯座

1

快速操作也适用于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+"://")]

0

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

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

我通常通过PHP生成链接。


0

万一有人希望看到它分解成一个非常强大的功能

    function getBaseURL() {
        var loc = window.location;
        var baseURL = loc.protocol + "//" + loc.hostname;
        if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
        // strip leading /
        var pathname = loc.pathname;
        if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
        var pathParts = pathname.split("/");
        if (pathParts.length > 0) {
            for (var i = 0; i < pathParts.length; i++) {
                if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
            }
        }
        return baseURL;
    }

这只是给出了整个网址。不是基本网址。
山姆

确实,不确定我要去哪里。我很早以前就开始使用服务器端代码进行设置了
nuander

0

简单

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

生成带有空src-name的img会强制浏览器自己计算基本URL,无论您是否拥有它/index.html或其他任何东西。


这似乎是所有解决方案中最优雅的解决方案,并且是唯一不重复浏览器逻辑的解决方案,这很好。我确实想知道它的便携性。HTML规范中是否有任何建议可以保证在所有浏览器中都能正常工作?
Matthijs Kooijman

@MatthijsKooijman取决于html规范的解释。如果您说长度为0的文件名是有效的资源名称...它确实与所有浏览器匹配。
Grim

了解浏览器的制作方式。您有几个程序员,(间接)希望构建一个浏览器。他们的第一个来源是html-specs。他们阅读了规范,这是他们真正想要解决的问题之一。您如何看待他们(所有人)在这种情况下的决定?
Grim

-2

分割并加入网址:

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

-4

将其放在标题中,以便在需要时可用。

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

您将获得http://localhost:81/your-path-filehttp://localhost/your-path-file

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.