我正在使用jQuery。如何获取当前URL的路径并将其分配给变量?
示例URL:
http://localhost/menuname.de?foo=bar&number=0
我正在使用jQuery。如何获取当前URL的路径并将其分配给变量?
示例URL:
http://localhost/menuname.de?foo=bar&number=0
当前回答
您可以简单地使用js本身获取路径,window.location或location将为您提供当前URL的对象
console.log(“Origin-”,location.Origin);console.log(“整个URL-”,location.href);console.log(“URL以外的路径-”,location.pathname);
其他回答
非常常用的前3个是
1. window.location.hostname
2. window.location.href
3. window.location.pathname
这是一个比许多人想象的更复杂的问题。一些浏览器支持内置JavaScript位置对象和通过window.location或document.location访问的相关参数/方法。然而,不同风格的Internet Explorer(6,7)不以相同的方式支持这些方法,(window.location.href?window.location.replace()不受支持),因此您必须通过始终编写条件代码来以不同的方式访问它们,以手持Internet Explorer。
因此,如果您有jQuery可用并已加载,那么您最好使用jQuery(location),正如其他人提到的那样,因为它解决了这些问题。然而,如果您正在通过JavaScript(即使用Google Maps API和位置对象方法)进行一些客户端地理位置重定向,那么您可能不想加载整个jQuery库并编写检查每个版本的InternetExplorer/Firefox/等的条件代码。
InternetExplorer让前端编码猫不高兴,但jQuery是一盘牛奶。
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
如果有人想要连接URL和哈希标签,请结合两个功能:
var pathname = window.location.pathname + document.location.hash;
在jstl中,我们可以使用pageContext.request.contextPath访问当前的url路径,
url = "${pageContext.request.contextPath}" + "/controller/path"
示例:在页面中http://stackoverflow.com/questions/406192这将给http://stackoverflow.com/controller/path