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
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 测距传感器数据手册i2c
- ¥15 RPA正常跑,cmd输入cookies跑不出来
- ¥15 求帮我调试一下freefem代码
- ¥15 matlab代码解决,怎么运行
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗
- ¥60 求一个简单的网页(标签-安全|关键词-上传)
- ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法