我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。


当前回答


// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""

host: "127.0.0.1:8000"

hostname: "127.0.0.1"

href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"

origin: "http://127.0.0.1:8000"

password: ""

pathname: "/projects/page/2"

port: "8000"

protocol: "http:"

search: "?name=jake&age=34"

username: ""
*/

url.searchParams.get('name')
// jake

url.searchParams.get('age')
// 34

url.searchParams.get('gender')
// null

其他回答

对于带有查询字符串的完整URL:

document.location.toString()

对于主机URL:

window.location

在jstl中,我们可以使用pageContext.request.contextPath访问当前的URL路径。如果要进行Ajax调用,请使用以下URL。

url = "${pageContext.request.contextPath}" + "/controller/path"

示例:对于页面http://stackoverflow.com/posts/36577223这将给http://stackoverflow.com/controller/path.

您可以使用以下方法获取带有哈希标记的当前URL位置:

JavaScript:

 // Using href
 var URL = window.location.href;

 // Using path
 var URL = window.location.pathname;

jQuery:

$(location).attr('href');

使用JavaScript获取当前URL:

window.location.toString();窗口.location.href

对于那些想要一个实际的URL对象的人,可能是一个以URL为参数的实用程序:

const url = new URL(window.location.href)

https://developer.mozilla.org/en-US/docs/Web/API/URL