skip to Main Content

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


  1. Chosen as BEST ANSWER

    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, &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

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
    

    After that, we prescribe the sending of data

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

    Done, now we can get this in server app.


  2. 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('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) {
                  //Do something with this.responseText;
                }
              };
              xhttp.open("POST", "<yoururl>", true);
              xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
              xhttp.send("id=" + id);
              
          }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search