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,这将导致对响应编写器的多次调用。



