【问题标题】:Remove query string "?" in HTML form method GET删除查询字符串“?”在 HTML 表单方法 GET
【发布时间】:2018-06-23 17:36:07
【问题描述】:

我有一个简单的 Google 图片搜索表单,可在新窗口中打开。当我想将表单参数更改为 Unsplash(在其 URL 搜索中不使用查询字符串)时,表单会继续发送查询字符串;(

HTML

<input type="radio" id="google" name="image" onclick="googleImages();" checked/>
<label for="google">Google Images</label>

<input type="radio" id="unsplash" name="image" onclick="unsplash();"/>
<label for="unsplash">Unsplash</label>

<form id="form" method="GET" action="https://www.google.com/search?q=">
    <input id="input" type="text" name="q" value="" required>
    <input type="submit" value="Search" onclick="this.form.target='_blank';">
    <input id="helper" type="hidden" name="tbm" value="isch">
</form>

JS

var
  form = document.getElementById("form"),
  input = document.getElementById("input"),
  helper = document.getElementById("helper");

function googleImages() {
  form.action="https://www.google.com/search?q=";
  input.name="q";
  helper.name="tbm";
  helper.value="isch";
}
function unsplash() {
  form.action="https://unsplash.com/search/photos/";
  input.name="";
  helper.name="";
  helper.value="";
}

如何创建一个从输出 URL 中删除查询字符串的函数? (并在单选选项需要时再次设置参数)

【问题讨论】:

    标签: javascript forms query-string


    【解决方案1】:

    因此,如果您不向 unsplash.com 发送任何参数,请不要使用表单提交。而是在 unsplash() 函数中使用 javascript 重定向。

    window.location.href = "https://unsplash.com/search/photos/";
    

    【讨论】:

      【解决方案2】:

      您在评论中澄清说,在调用 Unsplash 时,您需要将搜索字符串作为 URL 的一部分而不是作为查询字符串参数传递,如下所示:https://unsplash.com/search/photos/lion

      要使用您当前的设置,您需要做两件事:

      1. 将字符串添加到 URL,然后

      2. 禁用表单域。禁用的表单字段根本不会随表单一起发送; link to spec。 (当然,您也可以删除它们,但如果您在某个时候更改表单以使其具有target="_blank" 或类似名称,则删除它们会使允许 Unsplash 搜索后跟 Google 图片变得复杂搜索。)

      所以是这样的:

      function unsplash() {
        // #1
        form.action="https://unsplash.com/search/photos/" + encodeURIComponent(input.value);
        // #2
        input.disabled = true;
        helper.disabled = true;
        helper.disabled = true;
      }
      

      注意encodeURIComponent的使用。

      当然,如果您确实更新了页面以打开一个新窗口而不是替换当前窗口,您将更新您的 googleImages 函数以在这些输入上将 disabled 设置为 false(因为它将由unsplash 函数留下true)。不过,如果您要替换页面,则不必这样做。

      【讨论】:

      • 但是当 被禁用时,如何获取输入值(搜索词)?
      • @Lucas - 你说 Unslpash 不接受查询字符串参数。你没有说它怎么知道要搜索什么。如果不是通过查询字符串参数,您如何在form method="GET" 中发送该信息?
      • TJ,对不起我的英语不好。我想说的是,Google 图片使用了一些 URL 参数,例如 google.com/search?q=lion&tbm=isch,我可以在表单中复制这些参数。但是,Unsplash 不使用查询字符串 (?) 或参数 (q=value) 他们只使用“URL/值”unsplash.com/search/photos/lion 是否可以在 HTML 表单中重现这个?谢谢:)
      • @Lucas - 啊,我现在明白了!我已经更新了答案。 :-)
      猜你喜欢
      • 1970-01-01
      • 2010-11-10
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多