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