【问题标题】:Add # and ! to URL plus text from submitted search form添加 # 和 !从提交的搜索表单到 URL 和文本
【发布时间】:2018-04-02 18:52:02
【问题描述】:

我需要通过搜索将提交的文本添加到 URL。我在这里找到了一些代码 Add text to parameter before sumbit form ,它部分有效,但我需要添加的一些文本包括 #!和 ?添加到 url 时将转换为 %23%21 和 %3F。

堆栈溢出代码(最佳答案):

<form action="http://example.com/search" method="get" onsubmit="return addText();">
        <input type="text" name="q" id="q">
        <input type="submit">
    </form>

    <script>
    function addText(){
        document.getElementById("q").value += " BBBB CCCC"; // Whatever your value is
        return true;
    }
    </script>

我的 URL 需要返回如下内容:

http://example.com/?search=TEXT#!summaryList?skipMake=true&skipModel=true

到TEXT的url是通过的(TEXT是表单提交的q值),但是#!在摘要和之前?在跳过之前不要,并且 URL 需要整个字符串才能正常运行。

是否有一种简单的方法可以使用上面的代码使其工作,或者我最好找到一个 PHP 脚本?

谢谢!

【问题讨论】:

标签: javascript php html forms get


【解决方案1】:

使用encodeURIComponent() 对您的网址进行编码(以格式化#):

encodeURIComponent(myUrl)

使用decodeURIComponent() 解码您的网址:

decodeURIComponent(myUrl)

var myUrl = 'search=TEXT#!summaryList?skipMake=true&skipModel=true';
    
console.log('Encode URL', encodeURIComponent(myUrl));
console.log('Decode URL', decodeURIComponent(myUrl));

【讨论】:

    【解决方案2】:

    # 之后的任何内容都不会发送到服务器。如果您需要将其发送到服务器,则需要将其放在它自己的参数中(我使用extra 作为名称)。然后,您还需要确保它被正确编码,否则它也可以将该数据作为键/值发送。

    http://example.com/?search=TEXT&extra=summaryList%3FskipMake%3Dtrue%26skipModel%3Dtrue
    

    在您的服务器端,您需要decode it,然后获取键/值对

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多