首页 > 解决方案 > 以“URL/value”形式提交搜索表单,不带查询字符串“?q=value”

问题描述

我有一个在新窗口中打开的简单图像搜索表单:

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="poly();"/>
<label for="unsplash">Poly</label>


<form id="form" method="GET" action="https://www.google.com/search?q=">
  <input id="input" type="text" name="q" value="" required>
  <input id="button"  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"),
  button = document.getElementById("button"),
  helper = document.getElementById("helper");

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

代码在这里工作

问题

当我在搜索表单中更改为 Poly 时,查询字符串继续设置“?” 在 URL 输出中,在搜索结果页面上生成错误。

Google 图片使用一些 URL 参数,例如google.com/search?q=lion&tbm=isch,我可以在表单中复制这些参数。但是,Poly 不使用查询字符串 (?) 或参数 (param=value),它们只使用“URL/值”,例如poly.google.com/search/lion

问题

如何创建一个函数,当我选择 Poly 查询字符串“?” 被删除在提交时生成输出“URL/值”?换句话说,将搜索词(值)作为 URL 的一部分传递,而不需要任何查询或参数。

标签: javascripthtmlformssubmitquery-string

解决方案


看起来你只是在导航到不同的 url。您不希望或不需要这是表单提交。而不是在 JavaScript 中提交表单调用 window.location.href=。


推荐阅读