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

表单通过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:不用加隐藏字段的方法外,这样改动比较大~


加hidden...


我不理解题主所说“这样改动比较大”什么意思,貌似也只能是加hidden这种方法了,难道用js?

$('#form1').submit(function(){
location.href='index.php?param1=aaa&param2='+$('#para2').val();
return false;

})


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

规定原文:

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.

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要简洁一些。

【热门文章】
【热门文章】