如何在 Ajax 调用后重定向到调用的 URL?

huangapple go评论76阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2016年11月19日 00:32:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/40681963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定