在 GOLANG 中选中或不选中复选框

Bha*_*ash 5 html go

我正在尝试使用 GOLANG 构建一个简单的 Web 应用程序。目标是,当用户选中复选框时,它必须调用 API 端点,而当用户取消选中复选框时,它必须调用另一个 API 端点。下面是我在 HTML 中定义的表单action="p_up_dags/{{.}}"

PS: .Result是一个字符串列表。

{{ range .Result}}
<form action="/p_up_dags/{{.}}" method="POST">
     <br>  <input id={{.}} type="checkbox" name="{{.}}" value="{{.}}" >  {{.}}
    </form>
{{end}}
Run Code Online (Sandbox Code Playgroud)

高朗代码:

func p_up_dags(w http.ResponseWriter, r *http.Request){
     d_name = mux.Vars(r)["name"]
    //do something to check if the checkbox is checked or not
    //Something like this
    if d_name is checked
       {
       //http.Get("blah/blah")
       }
    else
      {
       //http.Get("foo/foo")
      }
}

func main(){
     router := mux.NewRouter().StrictSlash(true)
     router.HandleFunc("/p_up_dags/{name}",p_up_dags)
}
Run Code Online (Sandbox Code Playgroud)

Bha*_*ash 0

action=我自己解决了这个问题,通过在选中和取消选中复选框时更改表单中的属性,将其分成两部分。以下是更新后的表格action=""

{{range .Result}}
<form action="" name="{{.}}" method="POST">
    <label class="switch"> <input id="{{.}}" type="checkbox" class="box"  name="{{.}}" value="{{.}}"><span class="slider round"></span></label>
    <button onclick="myFunction(this.form,'{{.}}')">Pause/Unpause</button>
</form>
{{end}}
Run Code Online (Sandbox Code Playgroud)

JS 代码: 在这里,我们检查复选框是否选中或未选中,然后分别更改表单操作。if checked then action="blah/blah" else action="foo/foo"

<script>
function myFunction(form,result){
        var ch = document.getElementById(result)
        var formname = form.name;
        if(ch.checked == true){
            document[formname].action="/up_dags/"+result
        }
        else if(ch.checked == false){
            document[formname].action="/p_dags/"+result
        }
      }
</script>
Run Code Online (Sandbox Code Playgroud)

戈兰代码:

func p_dags(w http.ResponseWriter, r *http.Request){
   d_name := mux.Vars(r)["name"]
   _, err := http.Get(foo/foo/d_name)
}

func up_dags(w http.ResponseWriter, r *http.Request){
   d_name := mux.Vars(r)["name"]
   _, err := http.Get(blah/blah/d_name)
}

func main(){
    router := mux.NewRouter()
    router.HandleFunc("/p_dags/{name}",p_dags)
    router.HandleFunc("/up_dags/{name}",up_dags)
}

Run Code Online (Sandbox Code Playgroud)