首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >删除查询字符串"?“在HTML表单中,方法GET

删除查询字符串"?“在HTML表单中,方法GET
EN

Stack Overflow用户
提问于 2018-06-24 01:36:07
回答 2查看 2.3K关注 0票数 1

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

HTML

代码语言:javascript
复制
<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

代码语言:javascript
复制
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中删除查询字符串函数?(并在单选选项需要参数时重新设置参数)

请参阅此处的代码:http://jsbin.com/qitadepoxu/1/edit?html,js,output

EN

回答 2

Stack Overflow用户

发布于 2018-06-24 01:44:27

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

代码语言:javascript
复制
window.location.href = "https://unsplash.com/search/photos/";
票数 1
EN

Stack Overflow用户

发布于 2018-06-24 01:40:22

您已经在一条注释中阐明了,当调用Unsplash时,您需要将搜索字符串作为URL的一部分传递,而不是作为查询字符串参数,如下所示:https://unsplash.com/search/photos/lion

要在当前设置中做到这一点,您需要做两件事:

  1. 将字符串添加到URL,而
  2. 禁用表单域。禁用的表单域根本不随表单一起发送;link to spec。(当然,您也可以删除它们,但如果您在某个时候更改表单,使其具有target="_blank"或类似的内容,则删除它们将使在进行Unsplash搜索之后再进行谷歌图像搜索变得更加复杂。)

所以就像这样:

代码语言:javascript
复制
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 )。但是,如果您要替换页面,则不必执行此操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51003560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档