【问题标题】:Is there a way to escape special characters with coding applied only in the URL query string?有没有办法使用仅在 URL 查询字符串中应用的编码来转义特殊字符?
【发布时间】:2019-11-08 08:53:13
【问题描述】:

有问题的元素是一个 textarea 表单域。我添加到 URL 的查询字符串在除 textarea 之外的任何地方都可以正常工作。如果我在表单一的 textarea 字段中输入“Life is hard”,它会在目标表单中填充 textarea 字段:“Life%20is%20hard” 有没有办法在没有编码的情况下转义空格插件用户体验之外的任何东西?比如,就在查询字符串或参数中?

【问题讨论】:

    标签: javascript url parameter-passing textarea field


    【解决方案1】:

    查询字符串的内容是always URI 编码的,这意味着在使用它时,您必须always 对其进行URI 解码。假设您的查询字符串使用通常的name=value&name=value 形式:

    const entries = queryString.split("&").map(
        entry => entry.split("=").map(
            part => decodeURIComponent(part)
        )
    );
    

    entries 现在是一个由[key, value] 数组组成的数组,其中包含查询字符串的内容,已正确解码以供使用(例如填写textarea)。

    例子:

    const queryString = "this=that&a=b&text1=Life%20is%20good&x=y";
    
    const entries = queryString.split("&").map(
        entry => entry.split("=").map(
            part => decodeURIComponent(part)
        )
    );
    for (const [name, value] of entries) {
        if (name === "text1") {
            document.getElementById(name).value = value;
        } else {
            console.log(`Value for ${name}: ${value}`);
        }
    }
    <textarea id="text1"></textarea>

    如果name=value形式的查询字符串不是,如果它只是纯文本区域中你想要的,那就更简单了:

    theTextArea.value = decodeURIComponent(queryString);
    

    例子:

    const queryString = "Life%20is%20good";
    
    document.getElementById("text1").value = decodeURIComponent(queryString);
    <textarea id="text1"></textarea>

    【讨论】:

    • 谢谢。让我们试试这个。以下字符串有什么问题(仅限 textarea)yourawesomesite.wpmudev.host/create-profile?name-1={name-1}&name-2={name-2}&email-1={email-1}&url-1={url-1}&textarea-1= decodeURIComponent{textarea-1}
    • 附言。上述字符串适用于除 textarea 以外的所有字段。
    • @documentguy - 您不能在查询字符串中调用函数。
    【解决方案2】:

    url会自己编码,%20是这样的。

    捷径:

    decodeURI(str)
    

    或尝试:

    document.write(unescape(str))
    

    【讨论】:

      猜你喜欢
      • 2012-06-19
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2011-10-08
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      相关资源
      最近更新 更多