繁体   English   中英

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

[英]How ajax will GET the data from the golang code?

我有一个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的成功功能中。 先感谢您。

以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的返回部分

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM