js获取url

发布日期: 2024-06-10
FontSize: 【
js获取url

由于js是前端脚本,无法像php那样去获取一些与服务器相关的数据。相比php获取url,js与url相关的属性更少,js获取url更加简单。

php获取完整的url需要拼接,js可以一次性获取完整的url。

应用:在网站登录时,通常登录后需要跳回到原来的页面,可以使用js获取当前完整的url,在跳转的时候添加到url中。

$(document).ready(function() {
	$('#login-btn').click(function() {
		// 获取当前页面的URL
		const currentUrl = window.location.href;

		// 跳转到登录页面,并附加当前页面的URL作为查询参数
		window.location.href = 'https://example.com/login?returnUrl=' + encodeURIComponent(currentUrl);
	});
});

js中与url相关的一些属性

属性 属性(php相似但不一定无全相同) 说明
window.location.href   获取完整的URL,包括协议、域名、路径、查询参数和锚点。
window.location.protocol $_SERVER['REQUEST_SCHEME'] 获取URL的协议,例如:http:或https:。
window.location.host $_SERVER['SERVER_NAME'] 获取URL的域名,如z.lichil.com。
window.location.hostname   获取URL的主机名,如lichil。
window.location.port $_SERVER['SERVER_PORT'] 获取URL的端口号,HTTP协议默认使用80端口,而HTTPS协议默认使用443端口。例如:80。
window.location.pathname $_SERVER['SCRIPT_NAME'] 获取URL的路径,如/path/to/page
window.location.search $_SERVER['QUERY_STRING'] 获取URL查询字符串是一个 URL 中问号(?)后面的部分。例如:?key=hello%20world。
window.location.hash   获取URL的锚点,如#php。

在线测试js获取url

测试结果将在浏览器控制台显示,通常按F12进入浏览器控制台,例如火狐浏览器、谷歌浏览器。

<script>
// 获取完整的URL
const url = window.location.href;
console.log("URL:", url);

// 获取URL的协议
const protocol = window.location.protocol;
console.log("Protocol:", protocol);

// 获取URL的域名
const host = window.location.host;
console.log("Host:", host);

// 获取URL的端口号
const port = window.location.port;
console.log("Port:", port);

// 获取URL的路径
const pathname = window.location.pathname;
console.log("Pathname:", pathname);

// 获取URL的查询参数
const search = window.location.search;
console.log("Search:", search);

// 获取URL的锚点
const hash = window.location.hash;
console.log("Hash:", hash);
</script>