dongou1970 2013-01-17 01:04
浏览 11
已采纳

如何在GAE GO中实施AJAX

I know it is possible to do an ajax post using jQuery Ajax but how does the call would return a value, text, html or json? Thanks!

  • 写回答

1条回答 默认 最新

  • douche3244 2013-01-17 01:19
    关注

    There's a very good primer on creating web applications in Go here: http://golang.org/doc/articles/wiki/

    The example for handling a POST is given in the saveHandler function:

    func saveHandler(w http.ResponseWriter, r *http.Request) {
        title := r.URL.Path[lenPath:]
        body := r.FormValue("body")
        p := &Page{Title: title, Body: []byte(body)}
        p.save()
        http.Redirect(w, r, "/view/"+title, http.StatusFound)
    }
    

    In your case, instead of redirecting, just return a string eg.

    func saveHandler(w http.ResponseWriter, r *http.Request) {
        value := r.FormValue("inputVal")
        err := saveFunction(value)
        if err == nil {
            fmt.Fprintf(w, "OK")
        } else {
           fmt.Fprintf(w, "NG")
        }
    }
    
    func main() {
        http.HandleFunc("/", indexHandler)
        http.HandleFunc("/save", saveHandler)
        http.ListenAndServe(":8080", nil)
    }
    

    .. and (since you're using jQuery), handle it with a callback as shown in http://api.jquery.com/jQuery.post/:

    $.post('/save', {inputVal: "banana"}, function(data) {
      if(data == "OK") {
        alert("Saved!");
      } else {
        alert("Save Failed!");
      }
    });
    

    If you want to return JSON, you'll need to learn how to Marshal your data, then return that like we return the string above.

    Here is a link to to the JSON documentation: http://golang.org/pkg/encoding/json/#Marshal

    A good way to get familiar with how to use it is to have a play around on http://play.golang.org, marshalling and unmarshalling structs and printing them out. Here's an example: http://play.golang.org/p/OHVEGzD8KW

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?