[英]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.