I am developing a web application in Go. I have a drop-down list, it is formed from a template.
<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>
The logic of the operation is as follows: the user selects a list item -> 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('ul');
ul.addEventListener('click', 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("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)
}
2
Answers
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.
Next, you need to register sending data from js.To do this, import the axios client
After that, we prescribe the sending of data
Done, now we can get this in server app.
You can send an AJAX request. In the code chunk below I’m getting the
li
elements (not theul
as you did) and add a click listener to each of them, I mine theid
as theinnerText
of theli
and then sending an AJAX request, passing theid
. 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.