V
V
Vladimir2019-11-10 22:35:23
JavaScript
Vladimir, 2019-11-10 22:35:23

Why does the script loop through each line dozens of times?

Good evening. I'm trying to display the menu, before that it was displayed for 1 second and disappeared, now I still managed to display it, but incorrectly ..
Please help ..
Client:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0,width=device-width,height=device-height,user-scalable=no">
  <title>Menu</title>
  <style type="text/css">
    nav {
      color: #555;
    }
  </style>
</head>
<body>

  <nav></nav>


  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>	

  <script type="text/javascript">

    var io = io('http://localhost:3000/');

      function makeMenuLevel(menuItems) {
         
            return `<ul>${menuItems.map(
              item =>`<li>${item.title}${item.children ? makeMenuLevel(item.children) : ''}</li>`
            ).join('')}</ul>`;
        
      }

      

          	$(document).on('click',(e) => {

          		var xhr = new XMLHttpRequest();

        var body = 'id=' + encodeURIComponent(123);

        xhr.open("POST", '/menu', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.send(body);

          	})

          	io.on('menu', (data) => {
            	const menu = makeMenuLevel(data)
            	$('nav').append(menu)
            	console.log(data)
          })

  </script>
</body>
</html>

server:
app.get('/menu', (req,res) => {
  res.sendFile(__dirname + '/menu.html')
})

app.post('/menu', (req,res) => {
  connection.query('SELECT * FROM menu', (err, result) => {
      if(err) {
        console.error(err);
        return;
      }
      const index = result.reduce((acc, row) => ({...acc, [row.id]: row}), {});
      var menu = [];
      for(const row of result) {
        if(row.parent_id === 0) {
          menu.push(row);
          continue;
        }
        const parent = index[row.parent_id];
        if(!parent) {
          console.warn(`Undefined parent with id ${row.parent_id}`);
          continue;
        }
        if(!parent.children) {
          parent.children = [];
        }
        parent.children.push(row);

        return io.emit('menu',menu)
      }
    });
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question