给小程序码上长长的参数传递装个“瘦身裤”!看过来!
2023-09-08 00:08:15
很多时候,我们都会遇到微信小程序传参过长而被截断的问题,这是因为 URL 中有特殊字符,导致参数被截断。为了解决这个问题,我们需要对参数进行编码,即使用 encodeURIComponent 函数将参数进行编码,然后在小程序中使用 decodeURIComponent 函数进行解码,这样就可以保证参数不被截断。此外,我们还可以使用 URLSearchParams 对象来处理参数,这样可以更方便地管理参数。
encodeURIComponent 与 decodeURIComponent 函数详解
encodeURIComponent 函数是对一个给定的字符串进行编码,将特殊字符(如空格、问号、井号等)编码为易于传输的格式。而 decodeURIComponent 函数则是将编码后的字符串解码回原始字符串。
encodeURIComponent 函数的语法如下:
encodeURIComponent(string)
其中,string 是要进行编码的字符串。
encodeURIComponent 函数会将字符串中的以下特殊字符进行编码:
- 空格(" ")
- 问号("?")
- 井号("#")
- 等号("=")
- 百分号("%")
- 反斜杠("/")
- 反引号("‘")
- 冒号(":")
- 分号(";")
- 加号("+")
- 减号("-")
- 小于号("<")
- 大于号(">")
decodeURIComponent 函数的语法如下:
decodeURIComponent(string)
其中,string 是要进行解码的字符串。
decodeURIComponent 函数会将字符串中的以下编码字符解码回原始字符:
%20
解码为空格%3F
解码为问号%23
解码为井号%3D
解码为等号%25
解码为百分号%2F
解码为反斜杠%60
解码为反引号%3A
解码为冒号%3B
解码为分号%2B
解码为加号%2D
解码为减号%3C
解码为小于号%3E
解码为大于号
URLSearchParams 对象详解
URLSearchParams 对象是一个可迭代的对象,可以用来存储和操作 URL 中的参数。URLSearchParams 对象的构造函数如下:
new URLSearchParams(init)
其中,init 可以是一个字符串、一个对象或另一个 URLSearchParams 对象。
URLSearchParams 对象的方法包括:
- append(name, value) :添加一个参数到对象中。
- delete(name) :从对象中删除一个参数。
- get(name) :获取一个参数的值。
- getAll(name) :获取一个参数的所有值。
- has(name) :检查对象中是否包含一个参数。
- set(name, value) :设置一个参数的值。
URLSearchParams 对象的属性包括:
- length :对象中参数的数量。
实例
以下是一个使用 encodeURIComponent 和 decodeURIComponent 函数对 URL 中的参数进行编码和解码的示例:
const url = "https://example.com/page?name=John Doe&age=30";
// 对参数进行编码
const encodedUrl = encodeURIComponent(url);
// 对参数进行解码
const decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // 输出:https://example.com/page?name=John Doe&age=30
以下是一个使用 URLSearchParams 对象来操作 URL 中的参数的示例:
const url = new URL("https://example.com/page?name=John Doe&age=30");
// 获取参数
const name = url.searchParams.get("name");
const age = url.searchParams.get("age");
console.log(name); // 输出:John Doe
console.log(age); // 输出:30
// 添加参数
url.searchParams.append("city", "New York");
// 删除参数
url.searchParams.delete("age");
// 获取所有参数
const params = url.searchParams.getAll("name");
console.log(params); // 输出:["John Doe"]
// 设置参数
url.searchParams.set("name", "Jane Doe");
// 获取参数数量
const length = url.searchParams.length;
console.log(length); // 输出:2
// 输出 URL
console.log(url); // 输出:https://example.com/page?name=Jane Doe&city=New York