需要通过按钮单击将golang数据发送到html

package main


import (

    "time"

    "fmt"

    "encoding/json"

    "net/http"

    

)

type GetTime struct{

    Current_time string `json:"date"`

}

func main(){

  t:=(time.Now().Format(time.RFC3339))

    ctime:=GetTime{Current_time:t}

    byteArray,err:=json.Marshal(ctime)

    {

        if err!=nil{

            fmt.Println(err)

        }

    }

    fmt.Println(string(byteArray))

}

我需要将上面提到的Go lang数据发送到Html表单,当按钮在Html页面中被点击时


三国纷争
浏览 96回答 1
1回答

拉风的咖菲猫

你可能很少花精力来解决这个问题。虽然我很无聊,所以我决定帮助你。这是您的后端:package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "time")type Response struct {&nbsp; &nbsp; CurrentTime string}func main() {&nbsp; &nbsp; http.Handle("/", http.FileServer(http.Dir("web")))&nbsp; &nbsp; http.HandleFunc("/get-time", func(rw http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; ctime := Response{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CurrentTime: time.Now().Format(time.RFC3339),&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; byteArray, err := json.Marshal(ctime)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; rw.Write(byteArray)&nbsp; &nbsp; })&nbsp; &nbsp; if err := http.ListenAndServe(":5000", nil); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }}您还需要位于 (web/index.html) 中的前端:<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="IE=edge">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Document</title></head><body>&nbsp; &nbsp; <button id="gt">get time</button>&nbsp; &nbsp; <div id="res"></div>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("gt").onclick = async (e) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var req = await fetch("\get-time").then(r => r.json())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("res").innerHTML = req.CurrentTime&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go