首页 > 解决方案 > 如何共享正确编码的网址?

问题描述

我目前正在开发一个购物应用程序,我想在其中通过GETurl 中的参数字符串共享用户列表。现在的问题是列表可能包含空格或变音符号。我试图通过使用 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;
}

标签: javascript

解决方案


我错过了一些非常明显的东西还是我只是使用了错误的功能?

你只完成了一半的工作。

对URLtext中的使用值进行了编码。

但是随后您将您的 URL 用作另一个 URL(那个whatsapp://send)中的参数值 - 而值您没有正确地进行 URL 编码。

window.location = "whatsapp://send?text=" + encodeURIComponent(message);

推荐阅读