douwen1549 2018-05-02 06:36 采纳率: 100%
浏览 341
已采纳

ajax如何从golang代码中获取数据?

我有一个 golang api,用于保存和检索表单中的数据。保存 HTML 表单中填充的数据是没问题的,它可以成功地将数据保存在 mongodb 的数据库中,在检索数据的情况下,它还将根据 html 表单字段中填写的电子邮件检索数据,但是它显示了 ubuntu 终端中的数据。下面是我正在尝试的代码:

Html form index.html file

<form id="form1" method="post">
    <input id= "firstname" type="text" name="FirstName"  placeholder="Enter your firstname"><br><br>
    <input id= "lastname" type="text" name="LastName" placeholder="Enter your lastname"><br><br>
    <input id= "email" type="text" name="Email" placeholder="Enter your email"><br><br>
    <input id= "mobile" type="text" name="Mobile" placeholder="Enter your mobile"><br><br>
    <button id= "button1" class="button" name="button" type="button" value="Submit">Submit</button>
    <button id= "button2" class="button" name="button" type="submit" value="Search">Search</button>
</form>

Ajax in index.html is :-

$(document).ready(function(){
    //IT will save the data 
    $('#button1').on('click', function(e){
        button=this.value;
        console.log(button);
        e.preventDefault();
        if (button === "Submit") {
            var FirstName =$("#firstname").val(),
            LastName =$("#lastname").val(),
            Email =$("#email").val(),
            Mobile =$("#mobile").val();
            console.log(FirstName);
            $.ajax({
                url:"/login",
                type:"POST",
                data: {'button':button, "first":FirstName, "last":LastName, "email":Email, "mobile":Mobile},
                success: function(results) {
                    console.log(results);
                    $('#response').html(results);
                }
            });
        }
    });
    // This will search and I want the result in the success
    $('#button2').on('click', function(e){
        button=this.value;
        console.log(button);
        e.preventDefault();
        var Email =$("#email").val();
        $.ajax({
            url:"/get-data",
            type: "GET",
            data:{'button':button,"email":Email},
            success: function(results){
                console.log(results)
                $('#response').html(results);
            }
        });
    });
 });

Main.go file

import (
 "fmt"
 "gopkg.in/mgo.v2"
 "gopkg.in/mgo.v2/bson"
 "html/template"
 "log"
 "net/http"
 "encoding/json"
)
type USER struct {
 FirstName string `json:"FirstName,omitempty"`
 LastName  string `json:"LastName,omitempty"`
 Email     string `json:"Email,omitempty"`
 Mobile    string `json:"Mobile,omitempty"`
}
func login(w http.ResponseWriter, r *http.Request) {
 fmt.Println("method:", r.Method)
 if r.Method == "GET" {
    t, _ := template.ParseFiles("index.html")
    t.Execute(w, nil)
 } else {
    r.ParseForm()
    fmt.Println(r.Form)
    if r.Form["button"][0] == "Submit" {
        fmt.Println(r.Form)
        session, err := mgo.Dial("mongodb://127.0.0.1:27017/user")
        if err != nil {
            panic(err)
        }
        defer session.Close()
        session.SetMode(mgo.Monotonic, true)
        c := session.DB("user").C("profile")
        doc := USER{
            FirstName: r.Form["first"][0],
            LastName:  r.Form["last"][0],
            Email:     r.Form["email"][0],
            Mobile:    r.Form["mobile"][0],
        }
        err = c.Insert(doc)
        if err != nil {
            panic(err)
        }
        fmt.Println("FistName:", r.Form["first"][0])
        fmt.Println("LastName:", r.Form["last"][0])
        fmt.Println("Email:", r.Form["email"][0])
        fmt.Println("Mobile:", r.Form["mobile"][0])
    }
 }
}

func AllData(w http.ResponseWriter, r *http.Request){
 fmt.Println("method:", r.Method)
 if r.Method == "GET" {
    r.ParseForm()
    fmt.Println(r.Form)
     if r.Form["button"][0] == "Search" {
        fmt.Println(r.Form)
        fmt.Println(r.Form["email"][0])
        session, err := mgo.Dial("mongodb://127.0.0.1:27017/user")
        if err != nil {
            panic(err)
        }
        defer session.Close()
        session.SetMode(mgo.Monotonic, true)
        c := session.DB("user").C("profile")
        result := Users{}
        err = c.Find(bson.M{"email": r.Form["email"][0]}).All(&result)
        fmt.Println(result)
        b, err := json.MarshalIndent(result, "", "  ")
        if err != nil {
            panic(err)
        }
        fmt.Printf("%s
", b)
    }
 }
}

func main() {
  http.HandleFunc("/login", login)
  http.HandleFunc("/get-data", AllData)
  err := http.ListenAndServe(":9090", nil)
  if err != nil {
      log.Fatal("ListenAndServe: ", err)
  }
}

用GET / code 方法请求数据时,我应该做什么,才能让结果成功显示在 ajax 函数中?先提前谢谢你。

  • 写回答

1条回答 默认 最新

  • doumu4032 2018-05-02 06:57
    关注

    Send the response header of Data function in json format and write the response of json which can be received in success of $.ajax

    func AllData(w http.ResponseWriter, r *http.Request) {
        fmt.Println("method:", r.Method)
        if r.Method == "GET" {
                // your code ....
               b, err := json.MarshalIndent(result, "", "  ")
               if err != nil {
                   panic(err)
               }
               fmt.Printf("%s
    ", b)
               // set header to 'application/json'
               w.Header().Set("Content-Type", "application/json")
               // write the response
               w.Write(b)
           }
        }
    }
    

    Also there is an error in your code where you are returning from handler func AllData either create a middleware if you wants to do some modification in result or remove the return part of handler AllData

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化