Tengo este script que crea dinámicamente divs. Me gustaría pasar parámetros al controlador y poder visualizar el formulario de reserva después de hacer clic en el botón Reservar. Con thymeleaf lo haría así th:href="@{/hotels/{id}/booking-form(id=*{id})}" sin embargo, no estoy muy seguro de cómo puedo usar thymeleaf dentro de este creado dinámicamente división
Así que probé con javascript, pero, por supuesto, no funciona, por lo que agradecería mucho si alguien me dice qué estoy haciendo mal y cómo puedo obtener la identificación y pasarla al controlador.
<script type="text/javascript" th:inline="javascript"> document.getElementById('showAll').addEventListener('click', showAll); function showAll() { fetch('http://localhost:8080/accommodations') .then(response => { return response.json() }) .then((data) => { let output = `<h2> Search Results </h2>`; data.forEach(function (hotel) { output += ` /some divs here/ <!-- Book Now button --> <div class="d-flex justify-content-end mt-1"> <div class="btn btn-primary text-uppercase" id="bookingBtn" data-hotel-id="' + hotel.id + '" >Book Now</div> </div> </div>`; }); document.getElementById('output').innerHTML = output; }) } function booking() { let hotelId = $(this).data('hotel-id') fetch('http://localhost:8080/hotels/' + hotelId + '/booking-form', { method: 'POST' }) } document.getElementById('bookingBtn').addEventListener('click', booking); </script>Cuando usa literales de plantilla para crear una cadena, puede incluir variables de esta manera ${var} . Entonces, en su caso, debe hacer data-hotel-id="${hotel.id}"
data.forEach(function(hotel) { output += ` /some divs here/ <!-- Book Now button --> <div class="d-flex justify-content-end mt-1"> <div class="btn btn-primary text-uppercase" id="bookingBtn" data-hotel-id="${hotel.id}" >Book Now</div> </div> </div>`; });