URL 传值在 JavaScript 中是一种常见的数据传递方式。
基础概念:
通过 URL 的查询字符串(问号 ?
后面的部分)来传递参数和对应的值。
优势:
类型:
常见的有查询字符串参数形式,如 https://example.com/page?param1=value1¶m2=value2
。
应用场景:
可能出现的问题及原因:
解决方法:
localStorage
或 sessionStorage
)或通过服务器端进行传递。示例代码: 发送带有参数的跳转:
let param1 = "value1";
let param2 = "value2";
window.location.href = `https://example.com/page?param1=${encodeURIComponent(param1)}¶m2=${encodeURIComponent(param2)}`;
接收参数:
function getQueryParam(name) {
let queryStr = window.location.search.substring(1);
let paramsArray = queryStr.split('&');
for (let i = 0; i < paramsArray.length; i++) {
let pair = paramsArray[i].split('=');
if (decodeURIComponent(pair[0]) === name) {
return decodeURIComponent(pair[1]);
}
}
return null;
}
let param1 = getQueryParam('param1');
let param2 = getQueryParam('param2');
领取专属 10元无门槛券
手把手带您无忧上云