javascript - 如何共享正确编码的网址?
问题描述
我目前正在开发一个购物应用程序,我想在其中通过GET
url 中的参数字符串共享用户列表。现在的问题是列表可能包含空格或变音符号。我试图通过使用 Javascript 的函数encodeURIComponent来避免错误,这就是我的代码中出现错误的地方。
为了调试,我在控制台中记录了生成的 url。这里空格和变音符号被正确编码。但是当我连接 url 和自记录以来我没有触及的参数时,列表是原始格式,包含所有非法字符。我错过了一些非常明显的东西还是我只是使用了错误的功能?
这是我的代码:
function shareList() {
let text = "";
let boxes = getList(); //returns a list like [..., "Smoothie Purple;selectGetranke;0", "Smoothie Yellow;selectGetranke;0", ...]
for (let i = 0; i < boxes.length; i++) {
text += boxes[i] + ",";
}
if (text.length > 0) {
text = text.substring(0, text.length - 1);
}
//forms the list into a string: ...,Smoothie Purple;selectGetranke;0,Smoothie Yellow;selectGetranke;0,...
text = encodeURIComponent(text);
text = "https://example.com/?lst=" + text;
console.log(text); //logs https://example.com/?lst=...%2CSmoothie%20Purple%3BselectGetranke%3B0%2CSmoothie%20Yellow%3BselectGetranke%3B0%2C...
sendWhatsApp(text); //sends the link https://example.com/?lst=...,Smoothie Purple;selectGetranke;0,Smoothie Yellow;selectGetranke;0,...
}
function sendWhatsApp(message) {
window.location = "whatsapp://send?text=" + message;
}
解决方案
我错过了一些非常明显的东西还是我只是使用了错误的功能?
你只完成了一半的工作。
您对URLtext
中的使用值进行了编码。
但是随后您将您的 URL 用作另一个 URL(那个whatsapp://send
)中的参数值 - 而该值您没有正确地进行 URL 编码。
window.location = "whatsapp://send?text=" + encodeURIComponent(message);
推荐阅读
- java - 如何使用 Retrofit 返回字符串创建 void 方法?
- matlab - 在 MATLAB 中分离图像中的重叠边缘以获得准确的计数
- python - 使用 colab 和 windows 10,以及 chrome 版本 64b 和 chrome 驱动程序 32b,我更改了所有路径选项,但结果与以下相同
- javascript - 使用 NodeJS 加密进行 Java 解密
填充和 oepHash - flutter - Flutter:Flutter web 中容器内的滚动条
- reactjs - 如何根据用户身份验证在反应路由器中显示不同的导航栏?
- sql-server - 将 2008 ssis 转换为 2019 - 包配置在调试中不起作用
- c# - 如何返回列表中的值在表嵌套记录中不存在的结果,从表中返回出现和缺失值
- javascript - Javascript 读取文件 + 转换为 Base64 等待结果未定义
- c# - 如何在 CSV Helper 中有一个列在 c# 中接受逗号(,)