javascript - 提交表单后如何重定向到另一个 HTML 页面?
问题描述
我有一个包含表单元素的 HTML 页面。表单包含单选类型的输入和最后的按钮。我希望在单击按钮时调用一个 javascript 方法,该方法获取所选选项的值并重定向到 selectedChoice.html 页面。
这是我的 HTML 页面。
<html>
<head>
<script type="application/javascript" src="../js/navigation.js"></script>
</head>
<body>
<div id="chooseBodyPart">
<form>
<div class="question-text">
<p>Which body part is at dis-ease??</p>
</div>
<input class="radio-option" type="radio" name="bodyPartAtDisease" value="chest"> Chest <br>
<input class="radio-option" type="radio" name="bodyPartAtDisease" value="head"> Head <br>
<input class="radio-option" type="radio" name="bodyPartAtDisease" value="shoulders"> Shoulders <br>
<input class="radio-option" type="radio" name="bodyPartAtDisease" value="eyes"> Eyes <br>
<input class="radio-option" type="radio" name="bodyPartAtDisease" value="ears"> Ears <br>
<input class="radio-option" type="radio" name="bodyPartAtDisease" value="heart"> Heart <br>
<button onclick="redirectToNextPageBasedOnResponse();">Proceed</button>
</form>
</div>
</body>
</html>
下面是我的js。
function getListOfChoices(form) {
var choices = form.getElementsByTagName("input");
return choices;
}
// list of choices should be passed to this method and name of checked choice should be returned.
// In case no choice is selected the return null
function getNameOfCheckedChoice(choices) {
var selectedChoice = null;
for (var choiceNumber = 0; choiceNumber < choices.length; choiceNumber++) {
if (choices[choiceNumber].checked) {
selectedChoice = choices[choiceNumber].value;
break;
}
}
return selectedChoice;
}
function redirectToNextPageBasedOnResponse() {
var divContainingForm = document.getElementById("chooseBodyPart");
var form = divContainingForm.getElementsByTagName("form")[0];
var choices = getListOfChoices(form);
var selectedChoice = getNameOfCheckedChoice(choices);
window.location.href = "http://" + window.location.host + "/html/" + selectedChoice + ".html";
}
代码的工作正是我想要的,但是一旦控制从 redirectToNextPageBasedOnResponse() 返回,URL 不会更改为我编码的内容,而是在现有 URL 中插入一个查询参数,其值等于所选选项。
有人可以解释发生了什么吗?
解决方案
欢迎来到堆栈溢出!
请检查
window.location=url
或者
history.pushState({}, "title", url);
反而。
推荐阅读
- r - 无法使用 paste() 分离 R 包
- javascript - 如何组合/合并日期,然后在打字稿中按升序排序
- python-3.x - Discord.py 帮帮我
- ios - Swift IOS Display AR QuickLook预览下载的usdz模型
- algorithm - Hackerearth 上这个(Benny 和 Segments)问题的正确解决方案是什么?
- kubernetes - 使用 Ingress 规则在外部公开带有 clusterIP 服务的 kubernetes Dashboard
- react-native - 怎么修 ';' React-Native 中的预期错误
- java - 在 Windows 上运行的 Java - 如何为不在 PATH 中的命令执行 cmd?
- r - 在 Shiny 中渲染本地图像文件
- list - 向 Flutter 中的现有列表添加另一个属性