在JavaScript中,URL传递中文出现乱码通常是由于字符编码不一致或不正确导致的。以下是相关的基础概念、原因及解决方法:
%20
。encodeURIComponent
函数进行编码。encodeURIComponent
函数进行编码。decodeURIComponent
函数。decodeURIComponent
函数。<head>
部分指定字符集:<head>
部分指定字符集:以下是一个完整的示例,展示了前端如何进行URL编码,后端如何进行解码:
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>URL编码示例</title>
</head>
<body>
<script>
let chineseText = "中文";
let encodedText = encodeURIComponent(chineseText);
let url = "http://example.com/search?q=" + encodedText;
console.log(url); // 输出: http://example.com/search?q=%E4%B8%AD%E6%96%87
</script>
</body>
</html>
后端代码(Node.js):
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
const decodedText = decodeURIComponent(queryObject.q);
console.log(decodedText); // 输出: 中文
res.end();
}).listen(3000);
通过以上方法,可以有效解决JavaScript中URL传递中文乱码的问题。