ajax如何从golang代码中获取数据? [英] How ajax will GET the data from the golang code?

查看:227
本文介绍了ajax如何从golang代码中获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Html表格index.html文件

 < form id =form1method =post> 
< input id =firstnametype =textname =FirstNameplaceholder =输入您的名字>< br>< br>
< input id =lastnametype =textname =LastNameplaceholder =Enter your lastname>< br>< br>
< input id =emailtype =textname =Emailplaceholder =输入您的电子邮件>< br>< br>
< input id =mobiletype =textname =Mobileplaceholder =Enter your your mobile>< br>< br>

index.html中的Ajax是: -

< $($'$'$> $ $ $ $'$'$'$'$'$'$'$'$'$' ,函数(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,
类型:POST,
数据:{'button':按钮,first:名字,last:姓氏,email :结果);
('#response')。html(results);
}
});
}
});
//这将搜索并且我想要成功的结果
$('#button2')。on('click',function(e){
button = this.value;
console.log(button);
e.preventDefault();
var Email = $(#email)。val();
$ .ajax({
url:/ get-data,
类型:GET,
数据:{'button':button,email:Email},
success:function结果){
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: 名字,omitempty`
姓氏字符串`json:姓氏,omitempty`
电子邮件字符串`json:电子邮件,omitempty`
移动字符串`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)
}
推迟session.Close()
session.SetMode(mgo.Monotonic,true)
c:= session.DB(user)。C(profile)
doc:= USER {
名字:r.Form [ first] [0],
姓氏:r.Form [last] [0],
电子邮件:r.Form [email] [0],
手机: 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]})。(& result)
fmt.Println(result)
b,err:= json.MarshalIndent(result,,)
if err!= nil {
panic(err)
}
fmt.Printf( %s\\\
,b)
}
}
}

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

我应该如何处理从golang接收的数据到ajax GET 方法请求点击ton搜索和结果将显示在ajax的成功函数中。先谢谢你。 以json格式发送 Data 函数的响应头并写入可以在 $。ajax $

成功接收json的响应。

  func AllData(w http.ResponseWriter,r * http.Request){
fmt.Println(method:,r.Method)
if r.Method ==GET{
//你的代码....
b,err:= json.MarshalIndent(result,,)
if err!= nil {
panic(err)
}
fmt.Printf(%s \ n,b)
//将标题设置为'application / json'
w.Header()。Set(Content-Type ,application / json)
//写回应
w.Write(b)
}
}
}

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


I have a golang API for saving and retrieving the data from the form. Saving the data filled in the HTML form is okay. Means it will save the data in database of mongodb successfully but in case of retrieving the data it will retrieve the data on the basis of the email filled in the field of the html form is successful but it shows the data in the terminal of the ubuntu. Below is the code I'm trying for this:-

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\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)
  }
}

What should I do for receiving the data from golang to the ajax GET method request click on the button search and result will display in the success function of the ajax. Thank you in advance.

解决方案

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

这篇关于ajax如何从golang代码中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆