如何将下拉列表中的数据发送到服务器?

huangapple go评论84阅读模式
英文:

How to send data from the drop-down list to the server?

问题

我正在使用Go开发一个Web应用程序。我有一个下拉列表,它是从一个模板中生成的。

<div class="dropdown">
    <button onclick="myFunction()" class="dropbtn">删除服务</button>
    <ul id="myDropdown" class="dropdown-content">
      {{range .}}
      <li>{{.Id}}</li>
      {{end}}
    </ul>
  </div>
<script>
  function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
  }
  window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
      var dropdowns = document.getElementsByClassName("dropdown-content");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
        }
      }
    }
  }
</script>

操作逻辑如下:用户选择一个列表项 -> 选定的值必须传递给服务器以执行进一步的指令。

了解了这个问题后,我尝试首先在浏览器的控制台中输出数据:

  var ul = document.querySelector('ul');
  ul.addEventListener('click', function (event) {
    var targetEl = event.target;
    console.log(targetEl.innerHTML)});

我做到了,但我不知道接下来该怎么做。
服务器代码如下所示:

func main() {
	r := httprouter.New()
	routes(r)
	err := http.ListenAndServe("localhost:4444", r)
	if err != nil {
		log.Fatal(err)
	}
	if err != nil {
		log.Fatal(err)
	}

}

func routes(r *httprouter.Router) {
	r.ServeFiles("/public/*filepath", http.Dir("public"))
	r.GET("/", controller.StartPage)
	r.GET("/auth", controller.LoginPage)
	r.POST("/login", controller.Log_in)
	r.POST("/add_uslugu", controller.Add_from_html)
}
英文:

I am developing a web application in Go. I have a drop-down list, it is formed from a template.

 &lt;div class=&quot;dropdown&quot;&gt;
    &lt;button onclick=&quot;myFunction()&quot; class=&quot;dropbtn&quot;&gt; Удалить услугу&lt;/button&gt;
    &lt;ul id=&quot;myDropdown&quot; class=&quot;dropdown-content&quot;&gt;
      {{range .}}
      &lt;li&gt;{{.Id}}&lt;/li&gt;
      {{end}}
    &lt;/ul&gt;
  &lt;/div&gt;
&lt;script&gt;
  function myFunction() {
    document.getElementById(&quot;myDropdown&quot;).classList.toggle(&quot;show&quot;);
  }
  window.onclick = function(event) {
    if (!event.target.matches(&#39;.dropbtn&#39;)) {
      var dropdowns = document.getElementsByClassName(&quot;dropdown-content&quot;);
      var i;
      for (i = 0; i &lt; dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains(&#39;show&#39;)) {
          openDropdown.classList.remove(&#39;show&#39;);
        }
      }
    }
  }
 &lt;/script&gt;

The logic of the operation is as follows: the user selects a list item -&gt; the selected value must be transmitted to the server to execute further instructions.

Understanding this problem, I tried to first output the data to the console in the browser:

  var ul = document.querySelector(&#39;ul&#39;);
  ul.addEventListener(&#39;click&#39;, function (event) {
    var targetEl = event.target;
    console.log(targetEl.innerHTML)});

I did it, but I have no idea what to do next.
The server code is represented below:

func main() {
	r := httprouter.New()
	routes(r)
	err := http.ListenAndServe(&quot;localhost:4444&quot;, r)
	if err != nil {
		log.Fatal(err)
	}
	if err != nil {
		log.Fatal(err)
	}

}

func routes(r *httprouter.Router) {
	r.ServeFiles(&quot;/public/*filepath&quot;, http.Dir(&quot;public&quot;))
	r.GET(&quot;/&quot;, controller.StartPage)
	r.GET(&quot;/auth&quot;, controller.LoginPage)
	r.POST(&quot;/login&quot;, controller.Log_in)
	r.POST(&quot;/add_uslugu&quot;, controller.Add_from_html)
}

答案1

得分: 1

你可以发送一个AJAX请求。在下面的代码块中,我获取了li元素(而不是你所做的ul),并为每个元素添加了一个点击监听器。我将liinnerText作为id,然后发送一个带有id参数的AJAX请求。我不知道这个请求应该发送到哪个路径,所以你需要用你自己的路径替换它。我也不确定你需要什么类型的请求,我这里是发送了一个POST请求。最后,我为你创建了一个回调函数,目前什么也没做,但你需要用它来处理服务器的响应。

var ul = document.querySelectorAll('ul > li');
for (let li of ul) {
  li.addEventListener('click', function (event) {
    let id = li.innerText;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        // 在这里处理this.responseText的内容
      }
    };
    xhttp.open("POST", "<yoururl>", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("id=" + id);
  });
}
英文:

You can send an AJAX request. In the code chunk below I'm getting the li elements (not the ul as you did) and add a click listener to each of them, I mine the id as the innerText of the li and then sending an AJAX request, passing the id. I'm not aware of the path where this needs to be sent, so you will need to replace the path with your own and I'm also unsure what type of request you need, I was doing a POST request. Finally, I created a callback function for you that currently does nothing, but you will need it to handle server responses.

  var ul = document.querySelectorAll(&#39;ul &gt; li&#39;);
  for (let li of ul) {
        li.addEventListener(&#39;click&#39;, function (event) {
          let id = li.innerText;
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 &amp;&amp; this.status == 200) {
              //Do something with this.responseText;
            }
          };
          xhttp.open(&quot;POST&quot;, &quot;&lt;yoururl&gt;&quot;, true);
          xhttp.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
          xhttp.send(&quot;id=&quot; + id);
          
      }
  }

答案2

得分: 1

谢谢你的回答,我最终成功解决了这个问题,上面提出的方法可能更正确,但我想自己写出解决方法,也许对某人有帮助 如何将下拉列表中的数据发送到服务器?
首先,我们没有太多选项来从前端发送数据,需要编写一个处理JSON的处理程序。

type Service_struct struct {
    Service_name string
}

func Add_service(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
    var t Service_struct
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        fmt.Println(err)
    }
    err = json.Unmarshal(body, &t)
    if err != nil {
        panic(err)
    }
    log.Println(t)
}

接下来,你需要注册从JavaScript发送数据。为此,导入axios客户端。

<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>

然后,我们编写发送数据的代码。

var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
  var targetEl = event.target;
  var serviceName = targetEl.innerHTML;
  console.log(serviceName)
  axios.post('/add_service', {
    service_name: serviceName
  })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
});

完成了,现在我们可以在服务器应用程序中获取这些数据。

英文:

Thank you for your answer, I still managed to solve this problem, the method proposed above is probably more correct, but I want to write how I got to it myself, maybe it will help someone 如何将下拉列表中的数据发送到服务器?
Firstly , we don 't have so many options for sending data from the front, need to write a handler for processing json.

type Service_struct struct {
Service_name string
}
func Add_service(rw http.ResponseWriter, req *http.Request, p 
httprouter.Params) {
    var t Service_struct
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
	    fmt.Println(err)
    }
    err = json.Unmarshal(body, &amp;t)
    if err != nil {
	    panic(err)
    }
    log.Println(t)

}

Next, you need to register sending data from js.To do this, import the axios client

&lt;script src=&quot;https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js&quot;&gt;&lt;/script&gt;

After that, we prescribe the sending of data

var ul = document.querySelector(&#39;ul&#39;);
ul.addEventListener(&#39;click&#39;, function (event) {
  var targetEl = event.target;
  var serviceName = targetEl.innerHTML;
  console.log(serviceName)
  axios.post(&#39;/add_service&#39;, {
    service_name: serviceName
  })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

Done, now we can get this in server app.

huangapple
  • 本文由 发表于 2023年6月19日 19:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定