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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.