GOLANG中的复选框是否被选中

5
我正试图使用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}}

GOLANG代码:

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

这个表单不起作用,因为它在按钮提交时没有调用表单。您需要使用JavaScript来调用表单。Goland作为服务器语言使用。 - Vadim
你是对的 @Vadim。谢谢你的澄清。 - Bhanu Prakash
1个回答

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

JS 代码: 在这里,我们检查复选框是否被选中或未选中,然后相应地更改表单操作。 如果选中则 action="blah/blah",否则 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>

GOLANG 代码:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接