簡體   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