简体   繁体   English

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

[英]How to get base url with jquery or javascript?

In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.在 joomla php 中,我可以使用$this->baseurl来获取基本路径,但我想在 jquery 中获取基本路径。

The base path may be any of the following example:基本路径可以是以下示例中的任何一个:

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

The example may also change.这个example也可能会改变。

This one will help you...这个可以帮到你...

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

I think it will ok for you我想这对你没问题

var base_url = window.location.origin;

var host = window.location.host;

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

这将获得基本网址

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

This is an extremely old question, but here are the approaches I personally use ...这是一个非常古老的问题,但这里是我个人使用的方法......

Get Standard/Base URL获取标准/基本 URL

As many have already stated, this works for most situations.正如许多人已经说过的那样,这适用于大多数情况。

var url = window.location.origin;


Get Absolute Base URL获取绝对基本 URL

However, this simple approach can be used to strip off any port numbers.但是,这种简单的方法可用于剥离任何端口号。

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

Edit: To address the concern, posed by Jason Rice , the following can be used to automatically insert the correct protocol type ...编辑:为了解决由Jason Rice提出的问题,以下内容可用于自动插入正确的协议类型......

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


Set Base URL设置基本 URL

As a bonus -- the base URL can then be redefined globally.作为奖励 - 然后可以全局重新定义基本 URL。

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

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

在 JavaScript 中获取基本 url 的最简单方法

window.location.origin

This is not possible from javascript, because this is a server-side property.这在 javascript 中是不可能的,因为这是一个服务器端属性。 Javascript on the client cannot know where joomla is installed.客户端上的 Javascript 无法知道 joomla 的安装位置。 The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value ( phpBaseUrl ).最好的选择是以某种方式将$this->baseurl的值$this->baseurl到页面 javascript 中,然后使用此值 ( phpBaseUrl )。

You can then build the url like this:然后,您可以像这样构建 url:

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

Had the same issue a while ago, my problem was, I simply needed the base url.不久前遇到了同样的问题,我的问题是,我只需要基本网址。 There are a lot of detailed options here but to get around this, simply use the window.location object.这里有很多详细的选项,但要解决这个问题,只需使用window.location对象。 Actually type this in the browser console and hit enter to select your options there.实际上,在浏览器控制台中键入此内容,然后按 Enter 以在那里选择您的选项。 Well for my case it was simply:好吧,就我而言,这很简单:

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

But you can't say that the baseurl() of CodeIgniter(or php joomla) will return the same value, as it is possible to change the baseurl in the .htaccess file of these frameworks.但是你不能说 CodeIgniter(或 php joomla)的 baseurl() 会返回相同的值,因为可以更改这些框架的 .htaccess 文件中的 baseurl。

For example :例如 :

If you have an .htaccess file like this in your localhost :如果您的本地主机中有这样的 .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]

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

I've run into this need on several Joomla project.我在几个 Joomla 项目中遇到了这种需求。 The simplest way I've found to address is to add a hidden input field to my template:我发现的最简单的解决方法是在我的模板中添加一个隐藏的输入字段:

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

When I need the value in JavaScript:当我需要 JavaScript 中的值时:

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

Not as fancy as using pure JavaScript but simple and gets the job done.不像使用纯 JavaScript 那样花哨,但很简单,可以完成工作。

You can easily get it with:您可以通过以下方式轻松获取:

var currentUrl = window.location.href;

or, if you want the original URL, use:或者,如果您想要原始 URL,请使用:

var originalUrl = window.location.origin;

Here's a short one:这是一个简短的:

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

I would recommend for everyone to create HTML base tag in development, then assign the href dynamically, so in production whatever host a client uses, it will automacically addapt to it:我建议每个人在开发中创建 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>
 ...

So if you are in localhot:8080, you will reach every linked or referenced file from the base, eg: http://localhost:8080/some/path/file.html If you are in www.example.com, it will be http://www.example.com/some/path/file.html因此,如果您在 localhot:8080 中,您将从基础访问每个链接或引用的文件,例如: http://localhost:8080/some/path/file.html如果您在 www.example.com,它将是http://www.example.com/some/path/file.html

Also note that, every location you're on, you should not use references like globs in hrefs, eg: Parent location causes http://localhost:8080/ not http://localhost:8080/some/path/ .另请注意,您所在的每个位置,都不应该在 href 中使用像 glob 之类的引用,例如:父位置导致http://localhost:8080/而不是http://localhost:8080/some/path/

Pretent you reference all hyperlinks as full sentenced without the bas url.假装您将所有超链接都引用为完整的句子,而没有 bas url。

The format is hostname/pathname/search格式为主机名/路径名/搜索

So the url is :所以网址是:

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

For your case对于您的情况

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

So basically the baseurl = hostname = window.location.hostname所以基本上 baseurl = hostname = window.location.hostname

I am surprised that non of the answers consider the base url if it was set in <base> tag.我很惊讶,如果在<base>标签中设置了基本网址,那么没有答案会考虑基本网址。 All current answers try to get the host name or server name or first part of address.当前所有的答案都尝试获取主机名或服务器名或地址的第一部分。 This is the complete logic which also considers the <base> tag (which may refer to another domain or protocol):这是完整的逻辑,它也考虑了<base>标签(可能指的是另一个域或协议):

function getBaseURL(){
  var elem=document.getElementsByTagName("base")[0];
  if (typeof(elem) != 'undefined' && elem != null){
     return elem.href;
  }
  return window.location.origin;
}

Jquery format: jQuery 格式:

function getBaseURL(){
  if ($("base").length){
     return $("base").attr("href");
  }
  return window.location.origin;
}

Without getting involved with the logic above, the shorthand solution which considers both <base> tag and window.location.origin :在不涉及上述逻辑的情况下,同时考虑<base>标签和window.location.origin的速记解决方案:

Js: JS:

var a=document.createElement("a");
a.href=".";
var baseURL= a.href;

Jquery:查询:

var baseURL= $('<a href=".">')[0].href

Final note: for a local file in your computer (not on a host) the window.location.origin only returns the file:// but the sorthand solution above returns the complete correct path.最后注意:对于您计算机中的本地文件(不在主机上), window.location.origin仅返回file://但上面的 sorthand 解决方案返回完整的正确路径。

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

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

I was just on the same stage and this solution works for me我只是在同一个舞台上,这个解决方案对我有用

In the view在视图中

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

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

In js file you access base as a variable for example in your scenario:在 js 文件中,您将base作为变量访问,例如在您的场景中:

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

I do not remember where I take this information to give credit, if I find it I will edit the answer我不记得我从哪里获得了这些信息,如果我找到了,我会编辑答案

Easy简单

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

Generates a img with empty src-name forces the browser to calculate the base-url by itself, no matter if you have /index.html or anything else.生成带有空 src-name 的 img 会强制浏览器自行计算 base-url,无论您是否有/index.html或其他任何内容。

Here's something quick that also works with file:// URLs.这里有一些也适用于file:// URL 的快速方法。

I came up with this one-liner:我想出了这个单行:

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

You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts.您提到example.com可能会更改,所以我怀疑实际上您需要基本 url 才能为您的脚本使用相对路径表示法。 In this particular case there is no need to use scripting - instead add the base tag to your header:在这种特殊情况下,不需要使用脚本 - 而是将基本标签添加到您的标题中:

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

I usually generate the link via PHP.我通常通过 PHP 生成链接。

In case anyone would like to see this broken out into a very robust function如果有人想看到这个分解成一个非常强大的功能

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

Getting the base url |Calls controller from js获取基本 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;
}
  }
}

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

Split and join the URL:拆分并加入 URL:

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

Put this in your header, so it will be available whenever you need it.把它放在你的标题中,这样你就可以随时使用它。

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

You will get http://localhost:81/your-path-file or http://localhost/your-path-file .您将获得http://localhost:81/your-path-filehttp://localhost/your-path-file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM