javascript url 传递参数中文乱码问题解决方案

在 JavaScript 中,传递 URL 参数时,如果参数包含中文字符,可能会出现乱码问题。解决这一问题可以使用 encodeURIComponent 和 decodeURIComponent 函数。这些函数会对 URL 参数进行编码和解码,确保特殊字符(包括中文字符)能够被正确传递和解析。

以下是一个完整的解决方案示例:

 1. 传递参数(编码)

在传递 URL 参数时,可以使用 encodeURIComponent 对参数进行编码:

javascript
// 中文参数
let param = "中文测试";

// 编码参数
let encodedParam = encodeURIComponent(param);

// 构建URL
let url = https://example.com?param=${encodedParam};
console.log(url);  // 输出:https://example.com?param=%E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95


 2. 接收参数(解码)

在接收 URL 参数时,可以使用 decodeURIComponent 对参数进行解码:

javascript
// 获取URL参数
let urlParams = new URLSearchParams(window.location.search);

// 获取并解码参数
let decodedParam = decodeURIComponent(urlParams.get('param'));
console.log(decodedParam);  // 输出:中文测试


 示例代码

下面是一个完整的示例,包括传递和接收中文参数:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>URL Parameter Example</title>
</head>
<body>
    <script>
        // 示例传递参数
        let param = "中文测试";
        let encodedParam = encodeURIComponent(param);
        let url = https://example.com?param=${encodedParam};
        console.log("Encoded URL: " + url);  // 输出编码后的URL

        // 示例接收参数(假设当前URL包含参数)
        let currentUrlParams = new URLSearchParams(window.location.search);
        let receivedParam = decodeURIComponent(currentUrlParams.get('param'));
        console.log("Decoded Parameter: " + receivedParam);  // 输出解码后的参数
    </script>
</body>
</html>

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值