登录
首页 >  Golang >  Go问答

使用 JavaScript 和 Ajax 从 Go 中检索变量和结构数据

来源:stackoverflow

时间:2024-02-23 14:57:22 178浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《使用 JavaScript 和 Ajax 从 Go 中检索变量和结构数据》,涉及到,有需要的可以收藏一下

问题内容

我目前正在尝试将变量(在本例中为 js 变量数据中的结构数组)发送到我的网站。另外,我想从我的 textfield 中读取一个字符串并用它作为参数触发一个函数。我的问题是,如何从 go/javascript 获取/接收/发送变量?目前它甚至不调用 fillchoicebox() 函数。我将其设置为 onclick 函数,但没有任何反应。代码示例会非常好。

这是我的 golang 代码:

//klimakammer struct
type klimakammer struct {
    name        string `json:"name"`
    hersteller  string `json:"hersteller"`
    ip          string `json:"ip"`
    solltemp    string `json:"solltemp"`
    isttemp     string `json:"isttemp"`
    sollfcht    string `json:"sollfcht"`
    istfcht     string `json:"istfcht"`
    kammerstart bool
    kammerstop  bool
}

//ct01 klimakammern erstellen
var ct01 = klimakammer{"ct01", "weiss", "10.0.62.22", "", "", "", "", false, true}

//kammern - fill klimakammer array
var kammern = []klimakammer{
    ct01,
}

func main() {

    fs := http.fileserver(http.dir("./static/"))
    http.handle("/", fs)

    http.listenandserve(":8080", nil)

    http.handlefunc("/", func(w http.responsewriter, r *http.request) {
        buff, _ := json.marshal(&kammern)
        fmt.fprintln(w, string(buff))
    })

}

和我的 js 代码:

function fillChoiceBox() {

   **//That was my first try (But it never found the URL "/getKammer"):**
 // $.ajax({
 //     url: "http://localhost:8080/getKammer",
 //     method: "GET",
 //     function(data) {
 //         var $dropdown = $("#Kammer");
 //         for( i=0; i <= data.length; i++) {
 //               $dropdown.append($("

解决方案


以下是从典型 go 服务器发送和获取数据的示例代码。在实施之前,我建议先浏览一下 this 博客,了解如何使用 go 编写 web 应用程序。

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type Foo struct {
    Field1 string `json:"field1"`
    Field2 int    `json:"field2"`
}

func main() {
    http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
        var f Foo
        if err := json.NewDecoder(r.Body).Decode(&f); err != nil {
            panic(err)
        }
        defer r.Body.Close()

        log.Println("foo: ", f)
        w.WriteHeader(http.StatusOK)
    })

    http.HandleFunc("/bar", func(w http.ResponseWriter, _ *http.Request) {
        f := Foo{"bar", 20}
        w.Header().Set("Content-Type", "application/json")
        if err := json.NewEncoder(w).Encode(&f); err != nil {
            panic(err)
        }
    })

    panic(http.ListenAndServe(":3030", nil))
}

/*
JS Code to post data:

$.ajax({
    url: "http://localhost:3030/foo",
    method: "POST",
    data: JSON.stringify({field1:"foo",field2:10}),
    success: function() {
        console.log('done');
    }
})

JS Code to get data:

$.ajax({
    url: "http://localhost:3030/bar",
    method: "GET",
    success: function(data) {
        console.log(data);
    }
})
*/

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>