英文:
How to redirect to calling url after ajax call?
问题
我有一个通过Ajax调用发布的控制器函数:
func AddLike(w http.ResponseWriter, r *http.Request) {
fmt.Println("form posted \n\n")
// 获取会话
sess := session.Instance(r)
var params httprouter.Params
params = context.Get(r, "params").(httprouter.Params)
Name := params.ByName("name")
// 做一些处理
// 如何返回到调用页面?
}
该控制器可以从多个不同的URL进行发布。
在当前情况下,当函数返回到Ajax发布的URL /addlike
时,我看到一个空白页面。
我想知道在处理完发布后如何返回/重定向到调用页面?
英文:
I have a controller function that is posted by ajax call:
func AddLike(w http.ResponseWriter, r *http.Request) {
fmt.Println("form posted \n\n")
// Get session
sess := session.Instance(r)
var params httprouter.Params
params = context.Get(r, "params").(httprouter.Params)
Name := params.ByName("name")
//do stuff
//How to return to calling page?
}
This controller can be posted from several differnet urls.
In the current situation, I see a blank page as the function returns to the url of ajax post, which is /addlike
.
I'm wondering how to return/redirect to the calling page after post being processed?
答案1
得分: 1
根据评论中的建议,您可以使用Referer
头和http.Redirect
来进行重定向响应。
func AddLike(w http.ResponseWriter, r *http.Request) {
// TODO: Your stuff.
redirectURL := r.Header.Get("Referer")
if redirectURL == "" {
// TODO: 在不知道要重定向到哪里时该怎么办
return
}
http.Redirect(w, r, redirectURL, http.StatusFound)
}
英文:
As suggested in the comments, you can use the Referer
(sic) header and http.Redirect
to respond with a redirection.
func AddLike(w http.ResponseWriter, r *http.Request) {
// TODO: Your stuff.
redirectURL := r.Header.Get("Referer")
if redirectURL == "" {
// TODO: What to do in case you don't know
// where to redirect.
return
}
http.Redirect(w, r, redirectURL, http.StatusFound)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论