¿Cómo hago para que este botón me redirija a otra página?
<button type="submit" onclick="register()">Create new account</button>Esta es la función que utiliza el botón:
function register() { let object = { "username": document.getElementById("username").value, "password": document.getElementById("password").value }; let json = JSON.stringify(object); let xhr = new XMLHttpRequest(); xhr.open("POST", '/api/user/new', false) xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8'); xhr.send(json); if (xhr.status != 200) { alert("Something went wrong!"); } else if (xhr.status == 200){ alert("Success!"); } }Quiero que el botón me redirija al archivo 'index.html'
Intente envolver el botón en una etiqueta de formulario como esta:
<form action="index.html"> <button type="submit" onclick="register()">Create new account</button> </form>Parece que esto ya ha sido respondido de manera bastante extensa: ¿Cómo redirijo a otra página web?
En resumen: hay varias formas de lograrlo:
// window.location window.location.replace('http://www.example.com') window.location.assign('http://www.example.com') window.location.href = 'http://www.example.com' document.location.href = '/path' // jQuery $(location).attr('href','http://www.example.com') $(window).attr('location','http://www.example.com') $(location).prop('href', 'http://www.example.com')Si desea ir allí después de una llamada exitosa de la función, coloque uno de estos en lugar de "alerta ("¡Éxito!");"
<form action="/action_page.php" method="get"> <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:</label> <input type="text" id="lname" name="lname"><br><br> <button type="submit">Submit</button> <button type="submit" formaction="/action_page2.php">Submit to another page</button> </form>Ejemplo Un formulario con dos botones de envío. El primer botón de envío envía los datos del formulario a "action_page.php", y el segundo lo envía a "action_page2.php":
Definición y uso El atributo de formación especifica dónde enviar los datos del formulario cuando se envía un formulario. Este atributo anula el atributo de acción del formulario.
El atributo de formación solo se usa para botones con type="submit".
Consulte este enlace: https://www.w3schools.com/tags/att_button_formaction.asp