簡體   English   中英

jquery,域,獲取 URL

[英]jquery, domain, get URL

如何使用 jquery 獲取域名?

為此,您不需要 jQuery,因為簡單的 javascript 就足夠了:

alert(document.domain);

看看它在行動:

 console.log("Output;"); console.log(location.hostname); console.log(document.domain); alert(window.location.hostname) console.log("document.URL : "+document.URL); console.log("document.location.href : "+document.location.href); console.log("document.location.origin : "+document.location.origin); console.log("document.location.hostname : "+document.location.hostname); console.log("document.location.host : "+document.location.host); console.log("document.location.pathname : "+document.location.pathname);

有關更多域相關值,請在線查看window.location的屬性。 您可能會發現location.host是更好的選擇,因為它的內容可能與document.domain不同。 例如,url http://192.168.1.80:8080將只有document.domain的 ipaddress ,但location.host的 ipaddress 和端口號。

編輯:

如果你不需要支持IE10,你可以簡單地使用: document.location.origin

原始答案,如果您需要遺留支持

您可以通過檢查位置對象來獲得所有這些以及更多信息:

location = {
  host: "stackoverflow.com",
  hostname: "stackoverflow.com",
  href: "http://stackoverflow.com/questions/2300771/jquery-domain-get-url",
  pathname: "/questions/2300771/jquery-domain-get-url",
  port: "",
  protocol: "http:"
}

所以:

location.host 

將是域,在本例中為 stackoverflow.com。 對於 url 的完整第一部分,您可以使用:

location.protocol + "//" + location.host

在這種情況下將是http://stackoverflow.com

不需要jQuery。

類似於之前的答案有

location.host

location global 也有更多關於當前 url 的有趣事實。 (協議、主機、端口、路徑名、搜索、哈希)

如果您像我一樣需要字符串,請使用此功能 - 它確實有效。

function getHost(url)
{
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;
}

但請注意,如果 URL 中有子域(例如 www.),它將與主機名一起返回。 相反,如果沒有子域,主機名也不會有。

您可以使用以下代碼獲取當前 URL 的不同參數

alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);

不需要 jQuery,使用簡單的 javascript:

document.domain

document.baseURI為您提供域 + 端口。 如果圖像標簽使用相對路徑而不是絕對路徑,則使用它。 可能已經解決了,但它可能對其他人有用。

var part = location.hostname.split('.');
var subdomains = part.shift();
var upperleveldomains = part.join('.');

二級域,你可能會使用

var sleveldomain = parts.slice(-2).join('.');

檢查這個

alert(window.location.hostname);

這將返回主機名作為 www.domain.com

如果您想知道“注冊域名”,請查看: http//lbolla.wordpress.com/2011/04/05/get-registered-domain-in-python-and-javascript/

我在Javascript和Python中實現了reg-dom-libs(http://www.dkim-reputation.org/regdom-libs/)。

//If url is something.domain.com this returns -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-z]+.)/,"");
}
//If url is something.domain.com this returns -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-zA-Z0-9]+.)/,"");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM