英文:
Processing multiple forms from an only template
问题
我有两个表单放在一个模板中,我该如何识别每个 HTML 表单,以便在处理程序中进行处理呢?
在 POST 处理程序代码中,是否可以获取表单名称?
我正在使用 nosurf,因此我必须在同一个请求中生成和检查令牌,也许我做错了...
<form action="/form" method="post" name="form1">
<label class="control-label">Set A</label>
<div class="controls">
<input type="text" id="my" name="my">
</div>
<div style="display:none;">
<input name="_formkey" type="hidden" value="{{.token}}">
</div>
</form>
<form action="/form" method="post" name="form2">
<label class="control-label">Set thing</label>
<div class="controls">
<input type="text" id="thing" name="thing">
</div>
<div style="display:none;">
<input name="_formkey" type="hidden" value="{{.token}}">
</div>
</form>
我的处理程序:
func myHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method{
case "GET":
data := map[string]interface{}{
"key": nosurf.Token(req),
}
if err := renderTemplate(w, "base", data); err != nil {
log.Error(err)
}
case "POST":
// 如何获取表单值?
if r.FormValue("my"){}
...
if r.FormValue("thing"){}
...
}
}
谢谢!
英文:
I have two forms into a template, how can I identify every html form in order
to process it into my handler?<br>
Is possible get the form name in the post handler code?<br><br>
I'm using nosurf, therefore I must generate and check the
token in the same request, maybe I'm doing wrong..
<form action="/form" method="post" name="form1">
<label class="control-label">Set A</label>
<div class="controls">
<input type="text" id="my" name="my">
</div>
<div style="display:none;">
<input name="_formkey" type="hidden" value="{{.token}}">
</div>
</form>
<form action="/form" method="post" name="form2">
<label class="control-label">Set thing</label>
<div class="controls">
<input type="text" id="thing" name="thing">
</div>
<div style="display:none;">
<input name="_formkey" type="hidden" value="{{.token}}">
</div>
</form>
My Handler
func myHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method{
case "GET":
data:=map[string]interface{}{
"key":nosurf.Token(req),
}
if err := renderTemplate(w, "base", data); err != nil {
log.Error(err)
}
case "POST":
// how?
if r.FormValue("my"){}
...
if r.FormValue("thing"){}
...
}
}
Thanks
答案1
得分: 1
在处理程序代码中获取表单名称是可能的吗?
我认为这是不可能的,但是你可以在另一个隐藏的输入字段中发送表单名称。
英文:
> Is possible get the form name in the post handler code?
I don't think that's possible, but you can send the form name in another hidden input field.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论