繁体   English   中英

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

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

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

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

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

这个example也可能会改变。

这个可以帮到你...

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

我想这对你没问题

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;

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

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

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

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

window.location.origin

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

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

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

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

window.location.origin
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/

我在几个 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;

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

var originalUrl = window.location.origin;

这是一个简短的:

 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

另请注意,您所在的每个位置,都不应该在 href 中使用像 glob 之类的引用,例如:父位置导致http://localhost:8080/而不是http://localhost:8080/some/path/

假装您将所有超链接都引用为完整的句子,而没有 bas 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>标签中设置了基本网址,那么没有答案会考虑基本网址。 当前所有的答案都尝试获取主机名或服务器名或地址的第一部分。 这是完整的逻辑,它也考虑了<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;

查询:

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

最后注意:对于您计算机中的本地文件(不在主机上), window.location.origin仅返回file://但上面的 sorthand 解决方案返回完整的正确路径。

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

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

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

在视图中

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

我不记得我从哪里获得了这些信息,如果我找到了,我会编辑答案

简单

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

生成带有空 src-name 的 img 会强制浏览器自行计算 base-url,无论您是否有/index.html或其他任何内容。

这里有一些也适用于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+"://")]
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

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

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

拆分并加入 URL:

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

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

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

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

暂无
暂无

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

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