英文:
Go martini handling of HTML form data
问题
我遇到了从HTML表单获取数据的问题。
模板显示在localhost:3000,我提交后被带到localhost:3000/results,显示"404页面未找到"的结果。URL中不包含任何表单字段。
以下是要翻译的代码部分:
package main
import (
"html/template"
"net/http"
"github.com/go-martini/martini"
)
func main() {
m := martini.Classic()
m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini
t, _ := template.ParseFiles("form.gtpl")
t.Execute(res, nil)
})
m.Get("/results", func(r *http.Request) string {
text := r.FormValue("text")
return text
})
m.Run()
}
模板内容如下:form.gtpl
<html>
<head>
<title>Title Here</title>
</head>
<body bgcolor="#E6E6FA">
<h1>Header Here</h1>
<form action="/results" method="POST">
Date: <input type="text" name="dated" size="10" value="01/12/2015">
Triggers: <input type="text" name="triggers" size="100" value="Trigger1|Trigger2"><br><br>
<textarea name ="text" rows="20" cols="150">random text here
</textarea>
<input autofocus type="submit" value="Submit">
</form>
</body>
</html>
英文:
I am having trouble getting data from the HTML form.
The template shows at localhost:3000, I submit and am taken to localhost:3000/results with a "404 page not found" results. The URL does not include any of the forms fields.
package main
import (
"html/template"
"net/http"
"github.com/go-martini/martini"
)
func main() {
m := martini.Classic()
m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini
t, _ := template.ParseFiles("form.gtpl")
t.Execute(res, nil)
})
m.Get("/results", func(r *http.Request) string {
text := r.FormValue("text")
return text
})
m.Run()
}
and the template is: form.gtpl
<html>
<head>
<title>Title Here</title>
</head>
<body bgcolor="#E6E6FA">
<h1>Header Here</h1>
<form action="/results" method="POST">
Date: <input type="text" name="dated" size="10" value="01/12/2015">
Triggers: <input type="text" name="triggers" size="100" value="Trigger1|Trigger2"><br><br>
<textarea name ="text" rows="20" cols="150">random text here
</textarea>
<input autofocus type="submit" value="Submit">
</form>
</body>
</html>
答案1
得分: 4
在你的表单中,你指定了method="POST"
,但是在服务器代码中,你使用了m.Get("/results",...)
。这一行应该改为m.Post("/results",...)
。Martini试图路由请求,但是没有定义POST /results
,只有GET /results
。
英文:
Notice in your form you've specified method="POST"
, but in the server code you have m.Get("/results",...)
. That line should be m.Post("/results",...)
. Martini is trying to route the request but there is no definition for POST /results
only GET /results
答案2
得分: 0
将 m.GET 更改为 m.POST,然后问题解决了。
英文:
changed m.GET to m.POST, and voilà fixed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论