如何修改绑定register函数的HTML按钮使其请求成功后跳转到index.html
解决方案
你不需要修改现有的HTML按钮代码,仅需调整register函数的请求成功分支逻辑即可实现跳转效果。
JavaScript提供了两种常用的页面跳转方案,你可以根据需求选择:
- 跳转后保留当前注册页的历史记录,用户可通过浏览器返回按钮回到注册页:使用
window.location.href = 'index.html' - 跳转后不保留注册页的历史记录,避免用户注册成功后误触返回键回到注册页:使用
window.location.replace('index.html')
修改后的完整代码
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!"); // 此处添加跳转逻辑,二选一即可 // 方案1:保留历史记录 window.location.href = 'index.html'; // 方案2:不保留历史记录,注释上一行,放开下一行即可 // window.location.replace('index.html'); } }
补充说明:如果你的
index.html放在站点根目录,也可以写为/index.html,适配不同层级目录下的注册页调用跳转。
内容的提问来源于stack exchange,提问作者Tomek Nowak
相关产品推荐
相关产品推荐

