在JavaScript中,页面间传值出现乱码通常是由于字符编码不一致导致的。以下是一些基础概念、优势、类型、应用场景以及解决方案:
<head>
标签中设置字符编码为UTF-8:<head>
标签中设置字符编码为UTF-8:以下是一个完整的示例,展示了如何在页面间传递参数并避免乱码:
发送页面(sender.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sender</title>
</head>
<body>
<script>
const param = encodeURIComponent('中文');
window.location.href = `receiver.html?param=${param}`;
</script>
</body>
</html>
接收页面(receiver.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Receiver</title>
</head>
<body>
<script>
const urlParams = new URLSearchParams(window.location.search);
const param = decodeURIComponent(urlParams.get('param'));
console.log(param); // 输出: 中文
</script>
</body>
</html>
通过以上方法,可以有效避免JavaScript页面间传值乱码的问题。
领取专属 10元无门槛券
手把手带您无忧上云