登录
首页 >  Golang >  Go问答

如何获取下拉列表中选定的项目?

来源:stackoverflow

时间:2024-04-15 12:09:34 404浏览 收藏

今天golang学习网给大家带来了《如何获取下拉列表中选定的项目?》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我有以下 html 文件:





如何使用go获取所选选项的值?

func main() {
    log.Println("started")
    http.HandleFunc("/upload", upload)
    log.Fatal(http.ListenAndServe(":8080", nil))
}


func upload(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        t, _ := template.ParseFiles("upload.html")
        t.Execute(w, nil)
    }

解决方案


首先,您必须在 html 中有一个表单和提交按钮才能将数据发送到路由。您的 html 中没有表单。

第二:在您的上传功能中,您可以执行以下操作:

r.parseform()
fmt.println(r.form["action"])

go 代码充当服务器,由于 html 文件是从用户的浏览器运行的,因此如果不将其发送到服务器,您就无法访问它。在此示例中,我将使用 http get。

假设你的html文件位于“/”下

首先,更改 html 文件以使用 get 形式:




现在,我们需要在 /upload 下捕获此 get 请求(因为表单重定向到 /upload)

func upload(w http.responsewriter, r *http.request) {
    if r.method == "get" {
        r.parseform()
        w.write([]byte(r.form["action"][0]))
    }
}

所以我们可以将其总结为以下 go 代码

package main

import (
    "net/http"
    "log"
)


var page = `


` func m(w http.ResponseWriter, r *http.Request) { w.Write([]byte(page)) } func upload(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { r.ParseForm() w.Write([]byte(r.Form["action"][0])) } } func main() { log.Println("started") http.HandleFunc("/", m) http.HandleFunc("/upload", upload) log.Fatal(http.ListenAndServe(":8080", nil)) }

好了,本文到此结束,带大家了解了《如何获取下拉列表中选定的项目?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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