我想在从上一页收集数据后向客户显示另一页。但我无法在服务器端重定向新的URL。这是我的逻辑:
我坚持第3步(这是流程的一个例子):
type Stuff struct{
List []string
}
func checkcheck(w http.ResponseWriter, r *http.Request) {
sinfo := Stuff{
List: some_slice
}
t, err := template.New("").Parse(tpl_ds)
checkErr(err)
err = r.ParseForm()
checkErr(err)
err = t.Execute(w, sinfo)
checkErr(err)
if r.Method == "POST" {
saveChoice(r.Form["choices"])
/* step 3: make user open another URL */
}
}
这是模板:
<html>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
data: $('form').serialize(),
});
});
});
</script>
<body>
<form method="POST">
{{range .List}}
<input type="checkbox" name="choices" value="{{.}}"> <span>{{.}}</span><br>
{{end}}
<input type="submit" value="Submit">
</form>
</body>
</html>
我可以知道如何重定向到新页面吗?
P.S。如果我将URL放在按钮上,那么服务器将不会运行saveChoice()
答案 0 :(得分:27)
http状态303是这里的适当响应。所以用它重定向请求。
if r.Method == "POST" {
saveChoice(r.Form["choices"])
http.Redirect(w, r, newUrl, http.StatusSeeOther)
}
如果您的newUrl
应该向浏览器返回正确的html页面,则不需要使用ajax。使用html表单。
<form action="/postHandler" method="post">
{{range .List}}
<input type="checkbox" name="choices" value="{{.}}"> <span>{{.}}</span><br>
{{end}}
<input type="submit" value="Submit">
</form>
表单的注意action
定义为/postHandler
。在那里放置运行saveChoice
函数的端点的名称。
为避免http: multiple response.WriteHeader calls
错误,您可以使用此代码。
func checkcheck(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
sinfo := Stuff{
List: some_slice
}
t, err := template.New("").Parse(tpl_ds)
checkErr(err)
err = r.ParseForm()
checkErr(err)
err = t.Execute(w, sinfo)
checkErr(err)
}
if r.Method == "POST" {
saveChoice(r.Form["choices"])
http.Redirect(w, r, newUrl, http.StatusSeeOther)
}
}
否则,服务器会尝试呈现表单和重定向的url,这将导致多次调用响应编写器。
答案 1 :(得分:1)
package main
import (
"net/http"
"html/template"
)
type data struct {
List string
}
func main() {
http.HandleFunc("/", check)
}
func check(w http.ResponseWriter, r * http.Request) {
if r.Method == "GET" {
sinfo: = data {
List: "Here is a list of the files Located with in",
}
var tpl_ds = "index.html"
//t, err := template.New("").Parse(tpl_ds)
t: = template.Must(template.ParseFiles(tpl_ds))
r.ParseForm()
t.Execute(w, sinfo)
}
if r.Method == "POST" {
saveChoice(r.Form["choices"])
http.Redirect(w, r, newUrl, http.StatusSeeOther)
}
}