开发者社区> 问答> 正文

表单通过GET提交时,如何提交到一个带参数的地址

<form id="form1" action="/index.php?param1=aaa">
    <input name="param2"></input>
</form>

form1提交的时候我期望跳转的网址是:/index.php?param1=aaa&param2=bbb

可是实际是:/index.php?param2=bbb

如何能够把param1带过去

PS:不用加隐藏字段的方法外,这样改动比较大~

展开
收起
杨冬芳 2016-06-14 16:46:43 2443 0
1 条回答
写回答
取消 提交回答
  • IT从业

    答案对人有帮助,有参考价值 0 答案没帮助,是错误的答案,答非所问

    采纳

    根据HTML的规定,通过GET方法提交表单时,action地址里的query string会被丢弃。

    规定原文:
    •HTML 4.0.1(http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4

    
    If the method is "get" and the action is an HTTP URI, the user agent
     takes the value of action, appends a `?' to it, then appends the form
     data set, encoded using the "application/x-www-form-urlencoded"
     content type.
    •HTML 5(http://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#form-submission-algorithm)
    
    
    Mutate action URL
     Let query be the result of encoding the form data
     set using the application/x-www-form-urlencoded encoding algorithm,
     interpreted as a US-ASCII string.
    
    Let destination be a new URL that is equal to the action except that
     its  component is replaced by query (adding a U+003F QUESTION
     MARK character (?) if appropriate).

    所以,要实现你的需求,使用hidden input,是最简单的、无需编程的方式。

    如果你嫌hidden input麻烦,那就遗憾了,没有更简单的方法了。

    还有一个使用javascript的方法,但需要编程,比hidden input的方式麻烦,具体做法是:

    监听form submit事件,onSubmit()时,依次做:

    1. 取出action的值,把query string(问号后面那一串)解析出来
    2. 往form里apeend两个hidden input元素,name和value使用上面第一步解析出来的结果
    3. 用form.submit()提交表单

    优点时,这个JS写好以后,无论你哪个页面有类似的需求,不管你有几个变量要提交到服务端,只要按你在这个主贴中给出的 form 标签那样,把query string写在action里,JS会自动把它转成hidden input,自适应的能力比较强,比手写hidden input要简洁一些。

    2019-07-17 19:38:09
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载