Tengo dos archivos html ( index.html y allUsers.html ) y un index.js de JavaScript. El index.html tiene un botón allUsersButton .
Mi objetivo es que cuando se haga clic en allUsersButton , debería ver la página allUsers.html y poder ver los datos obtenidos que deben inyectarse en el div llamado allUsersDivId .
Hasta ahora, no se cargan datos en la página allUsers.html y aparece un error en la consola "Error de tipo no detectado: no se pueden establecer las propiedades de nulo (estableciendo 'onclick')".
¿Deberían tanto index.html como allUsers.html tener el script vinculado en ellos? ¿Cuál es la mejor manera de armar esto?
índice.html
<body> <form action="http://localhost:7050/hello" method="POST"> <label for="username">User name:</label> <input type="text" id="username" name="username"><br><br> <input type="submit" value="Submit"> </form> <button type="button" id="allUsersButton">All Users</button> <script src="index.js"></script> </body>todosUsuarios.html
<body> <div id = "allUsersDivId"> </div> <script src="index.js"></script> </body> índice.js
Aquí tengo una función para obtener e insertar los datos en el div allUsersDivId que está en allUsers.html , y un onClick escuchando en allUsersButton que está en index.html .
document.getElementById("allUsersButton").onclick = function() {displayAllUsers()}; function displayAllUsers() { window.location.href='allUsers.html' fetch("http://localhost:7050/allusers") .then((response) => { if (response.ok) { return response.json(); } else { throw new Error("NETWORK RESPONSE ERROR"); } }) .then(data => { for(var i = 0; i < data.length; i++){ const userName = data[i].username const userNameDiv = document.getElementById("allUsersDivId") const heading = document.createElement("h1") heading.innerHTML = userName userNameDiv.appendChild(heading) } }) .catch((error) => console.error("FETCH ERROR:", error)); }¿Cuál es la mejor manera de vincular todo esto?