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 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
- ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
- ¥20 @microsoft/fetch-event-source 流式响应问题
- ¥15 ogg dd trandata 报错
- ¥15 高缺失率数据如何选择填充方式
- ¥50 potsgresql15备份问题
- ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
- ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
- ¥60 pb数据库修改与连接
- ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?