制作一个HTML按钮将我重定向到另一个页面



如何使此按钮重定向到另一个页面?

<button type="submit" onclick="register()">Create new account</button>

下面是按钮使用的函数:

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

我想让按钮重定向到'index.html'文件

尝试在表单标签中包装按钮:

<form action="index.html">
<button type="submit" onclick="register()">Create new account</button>
</form>

这个问题似乎已经得到了广泛的回答:我如何重定向到另一个网页?

总结:有很多方法可以达到这个目的:

// 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')

如果你想在函数成功调用后再去那里-用这些来代替"alert("Success!");">

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

的例子带有两个提交按钮的表单。第一个提交按钮将表单数据提交给"action_page.php",第二个提交给"action_page.php":

定义和用法formaction属性指定提交表单时将表单数据发送到何处。此属性覆盖表单的action属性。

formaction属性只用于type="submit"的按钮。

请参考此链接:https://www.w3schools.com/tags/att_button_formaction.asp

最新更新