JavaScript重定向表单提交

JavaScript redirect on form submission

本文关键字:表单提交 重定向 JavaScript      更新时间:2023-09-26

我正在尝试做一个练习,允许用户根据他们的搜索词被重定向到特定的本地网页。由于某些原因,window.location.replace不会重定向。我尝试了window的一种变体。在新标签页中打开登陆页的位置,这是有效的。任何帮助都是感激的!

html

<form name="form1" onsubmit="myFunction()">
Street Address:
<input type="text" id="streetaddress" required="true"><br>
Township:
<input type="text" id="township" required="true">
<br>
<input type="submit" onclick="return myFunction()" name="Search" value="Search">
</form>
<p id="demo"></p>

js

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "";
var nameValue1 = document.getElementById("streetaddress").value;
var nameValue2 = document.getElementById("township").value;
if (nameValue1.toUpperCase() === "1 MARJORAM DRIVE" && nameValue2.toUpperCase() === "LUMBERTON") {
window.location.replace("landingpage.html");
}
else {
document.getElementById("demo").innerHTML = "<font color='red'><p>0 results</p></font>";
return false;
}
}
</script>

我已经修改了我的代码实现建议的解决方案,但我仍然遇到同样的问题,页面不会重定向。我从原始代码中更改的行如下…

html

<form name="form1" onSubmit="return myFunction()">
<input type="submit" name="submit" class="submit" value="Search">

js

if (nameValue1.toUpperCase() === "1 MARJORAM DRIVE" && nameValue2.toUpperCase() === "LUMBERTON") {
window.location.href = 'landingpage.html';
}

修改window.location变量

window.location = "http://www.newsite.com/path/to/page";

对于本地托管的页面,使用以下命令:

window.location.href = "newlocation.html";