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

How to get base url with jquery or javascript?

本文关键字:URL 获取 javascript 何使用 jquery      更新时间:2023-09-26

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

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

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

example也可能发生变化。

我认为这对你来说很有效:

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

这个会帮助你...

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

这将获取基本网址

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

> document.baseURI 返回基本 URL,也尊重 <base/> 标记中的值https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI

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

获取标准/基本网址

正如许多人已经说过的那样,这适用于大多数情况。

var url = window.location.origin;


获取绝对基本网址

但是,这种简单的方法可用于剥离任何端口号。

var url = "http://" + location.host.split(":")[0];

编辑:为了解决杰森赖斯提出的问题,以下内容可用于自动插入正确的协议类型......

var url = window.location.protocol + "//" + location.host.split(":")[0];


设置基本网址

作为奖励 - 然后可以全局重新定义基本 URL。

document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";

JavaScript 中获取基本网址的最简单方法

window.location.origin

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

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

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;
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/

不久前遇到了同样的问题,我的问题是,我只需要基本网址。这里有很多详细的选项,但要解决这个问题,只需使用 window.location 对象即可。实际上在浏览器控制台中键入此内容,然后按回车键在此处选择您的选项。好吧,就我而言,它很简单:

window.location.origin

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

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

当我需要 JavaScript 中的值时:

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

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

您可以通过以下方式轻松获得它:

var currentUrl = window.location.href;

或者,如果您想要原始网址,请使用:

var originalUrl = window.location.origin;

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

所以网址是:

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 = 主机名 = window.location.hostname

我很

惊讶,如果它是在标签中设置的,则没有一个答案会考虑基本网址<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://但上面的sorthand解决方案返回完整的正确路径。

这是一个简短的:

const base = new URL('/', location.href).href;
console.log(base);

我建议大家在开发中创建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 的完整句子。

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

几乎和杰尼什的回答一样,但短了一点。

我只是在同一个舞台上,这个解决方案对我有用

在视图中

<?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

我不记得我把这些信息带到哪里来给予信任,如果我找到它,我会编辑答案

这里有

一个更简单的答案,window.location.href = window.location.origin;

容易

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

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

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[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+"://")]

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

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

我通常通过PHP生成链接。

如果有人希望看到它分解成一个非常健壮的功能

    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;
    }

拆分并加入 URL:

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

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

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

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

你会得到http://localhost:81/your-path-filehttp://localhost/your-path-file.