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

时间:2018-05-02 06:36:42

标签: jquery html ajax go

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

Html表单index.html文件

<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>

index.html中的Ajax是: -

$(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文件

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\n", b)
    }
 }
}

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

如何从golang接收数据到ajax GET方法请求点击按钮搜索,结果将显示在ajax的success函数中。先感谢您。

1 个答案:

答案 0 :(得分:0)

以json格式发送Data函数的响应头并写下json的响应,该响应可以在$.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\n", b)
           // set header to 'application/json'
           w.Header().Set("Content-Type", "application/json")
           // write the response
           w.Write(b)
       }
    }
}

你的代码中还有一个错误,你从处理程序func AllData返回,如果你想在结果中做一些修改或者删除处理程序AllData的返回部分,那么创建一个中间件