一.一个form有多个button提交, html5之前的解决方式
(1)HTML中定义多个type=submit的button,name相同,value不同
<form class="" method="get"> <div class="row "> <div class="col-1"> {{ filterform.ifchuhe|as_crispy_field }} </div> <div class="col-1"> {{ filterform.ifanzhi|as_crispy_field }} </div> </div> <input type="submit" class="btn btn-sm btn-primary" name="submit" value="查询"/> <input type="submit" class="btn btn-sm btn-default" name="submit" value="清空条件"/> <input type="submit" class="btn btn-sm btn-primary" name="submit" value="导出数据(excel)"/> {% if user.jg.level == '2' %} <input type="button" class=" btn btn-sm btn-primary m-1" value="调整区县" onclick="showModal()"/> {% endif %} </form>
#按钮点下后,提交form用tpye='submit'
如果不想提交,而是执行js的时,type='button'
(2)在后台,request.GET或POST去读取name,判断value,调用不同的逻辑
本例的form用get方法提交
def get(self, request, *args, **kwargs): if request.GET.get('submit') == '查询': elif request.GET.get('submit') == '清空条件': return redirect('d3:StudentSearchList') elif request.GET.get('submit') == '导出数据(excel)': return download_excel_data(request, self.get_queryset())
二、一个button提交多个form
(1)HTML中定义多个type=submit的button,name相同,value不同
<input type="button" value="Click Me!" onclick="submitForms()" />
js这样定义
#通过id 找form
submitForms = function(){ document.getElementById("form1").submit(); document.getElementById("form2").submit(); } #通过name找form submitForms = function(){ document.forms["form1"].submit(); document.forms["form2"].submit(); }
三、html5以后, form提交灵活多了
<!--原来的写法--> <form action="加上地址"> <button type="submit">提交</button> </form> <!--现在 写法--> <form > <button type="submit" formaction="第1个按钮的提交地址">btn1</button> <button type="submit" formaction="第2个按钮的提交地址">btn2</button> <button type="submit" formaction="第3个按钮的提交地址">btn3</button> </form>
<head> <title>formmethod属性示例</title> <meta charset="UTF-8"> </head> <form id="testform" action="serve.jsp">
<!-- 在这个表单中s1,s2都提交到 serve.jsp里--> <input type="submit" name="s1" value="v1" formaction="s1.jsp" formmethod="post">
<!-- 这个s1 提交到s1.jsp以这种post方式提交-->
<input type="submit" name="s2" value="v2" formaction="s2.jsp" formmethod="get">
<!--这个 s2提交到s2.jsp 以这种get方式提交 -->
<input type="submit"> <!--用系统默认server.jsp的提交--> </form>
<!DOCTYPE HTML> <html> <body> <form action="/example/html5/demo_form.asp" method="get" id="nameform1"> MYNAME:<input type="text" name="MYNAME" /><br /> </form> <form action="/example/html5/demo_form.asp" method="get" id="nameform2"> YOURBANE:<input type="text" name="YOURBANE" /><br /> </form> <p>下面的按钮位于 form 元素之外,但仍是表单的一部分。</p> <button type="submit" form="nameform1" value="Submit">提交_FORM1</button> <button type="submit" form="nameform2" value="Submit">提交_FORM2</button> </body> </html>
REFERENCE: https://www.w3school.com.cn/tags/att_button_formaction.asp
Internet Explorer 9 及更早 IE 版本不支持 formaction