js 通过url传参
模拟:
页面一(A.html)登录 传递参数 用户名 Uname 密码 Upassword
页面二(B.html)接收参数
页面一(A.html)
<body>
<form action="B.html">
<!-- 必须有 name -->
<input type="text" name="Uname"> // 用户名
<input type="text" name="Upassword"> // 密码
<input type="submit" value="提交">
</form>
</body>
效果如下
点击提交后 参数被放进url
当然不止一种传值,我们可以使用 window.location.href 或者 search 直接赋值
<button onclick="clis()">s</button>
<script>
let Uname = "chaliceJoker";
let Upassword = "Joker123";
function clis(){
window.location.href = "http://127.0.0.1:5501/B.html?Uname=" + Uname;
// window.location.search = "Upasword=" + Upassword // 缺少跳转,适用于a标签一类
}
</script>
页面二(B.html)
<script>
// 定义一个变量接收url
var query = location.search;
console.log(query)
// 定义一个变量截取?后的参数
let Vals= query.split("?");
console.log(Vals)
// 有多个参数时使用&分割
let OnecVal = Vals[1].split("&");
console.log(OnecVal);
// 循环这个对象使用等号接收 键 和 值
for(let i=0; i<OnecVal.length;i++){
let keyAval = OnecVal[i].split("=")
console.log(keyAval [0],keyAval [1])
}
</script>
最终拿到 用户名 密码