获取URL中的参数

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>获取URL中的参数</title>
</head>
<body>
<script type="text/javascript">
var url = 'http://www.manong.life/demo.html?name=张三&age=18';
var urlObject = new URL(url);
var urlSearchParams = new URLSearchParams(urlObject.search);

// 遍历所有参数
var entries = urlSearchParams.entries();
for (let param of entries) {
    console.log(param[0] + ' => ' + param[1]);
}
// name => 张三
// age => 18

// 获取指定参数
var name = urlSearchParams.get('name');
var age = urlSearchParams.get('age');
console.log('俺叫' + name + ',俺今年' + age + '岁。'); // 俺叫张三,俺今年18岁。
</script>
</body>
</html>

Copyright © 2023 码农人生. All Rights Reserved