jquery,domain,获取URL

Ale*_*exC 139 javascript dns jquery

如何用jquery获取域名?

Sam*_*son 328

你不需要jQuery,因为简单的javascript就足够了:

alert(document.domain);
Run Code Online (Sandbox Code Playgroud)

看到它的实际效果:

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);
Run Code Online (Sandbox Code Playgroud)

有关其他与域相关的值,请查看window.location在线属性.您可能会发现这location.host是一个更好的选择,因为它的内容可能不同document.domain.例如,url http://192.168.1.80:8080只有ipaddress document.domain,但是ipaddress和端口号都在location.host.

  • @ rob.alarcon这是一个[W3C推荐](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-2250147)并且在新旧浏览器中得到了广泛的支持.我所知道的唯一问题是某些浏览器([如Firefox](https://developer.mozilla.org/en-US/docs/DOM/document.domain#Notes))会让您写入此属性(只要新值是原始域的子域,每个规范只读. (7认同)
  • 我实际上建议使用`window.location.host`(作为bibby发布).我刚刚修复了一个错误,其中`document.domain`被设置为根域而不是子域. (4认同)
  • 需要更多JQuery. (3认同)

sup*_*ary 113

您可以通过检查location对象来获得所有这些以及更多:

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:"
}
Run Code Online (Sandbox Code Playgroud)

所以:

location.host 
Run Code Online (Sandbox Code Playgroud)

将是域,在这种情况下stackoverflow.com.对于网址的完整第一部分,您可以使用:

location.protocol + "//" + location.host
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这将是http://stackoverflow.com

不需要jQuery.


bib*_*bby 33

类似于那之前的答案

location.host
Run Code Online (Sandbox Code Playgroud)

全球位置也有关于当前网址的更多有趣事实.(协议,主机,端口,路径名,搜索,哈希)


Vov*_*pov 20

如果你需要像我这样的字符串,请使用此功能 - 它确实有效.

function getHost(url)
{
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;
}
Run Code Online (Sandbox Code Playgroud)

但请注意,如果URL中有子域(例如www.),它将与主机名一起返回.相反,如果没有子域,主机名也不会有.

  • 他说a.hostname将返回www.这是你域名的一部分.换句话说,这将是错误的:`getHost('http://www.google.com')=='google.com'`而这将是真的:`getHost('http://google.com ')=='google.com'` (2认同)

小智 9

您可以使用以下代码获取当前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);
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 6

不需要jQuery,使用简单的javascript:

document.domain
Run Code Online (Sandbox Code Playgroud)