gpt4 book ai didi

javascript - 在javascript中提交表单后页面重定向回来

转载 作者:行者123 更新时间:2023-11-30 10:02:08 25 4
gpt4 key购买 nike

我尝试使用 javascript 添加两个运算符然后我想在 ajax 中尝试它然后我想看看两个代码操作之间的区别但是每当我在 javascript 中实现添加我就卡住了因为页面显示结果一秒钟然后它重定向回来。谁能告诉我这段代码有什么问题吗?

<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script>
function loadFunction(){
//window.alert("hello");
var x= document.getElementById("d1");
var y =document.forms["myForm"]["op1"].value;
var z =document.forms["myForm"]["op2"].value;
x.innerHTML="<h2>" +(parseInt(y)+parseInt(z)) + "</h2>";
x.style.width="35%";
x.style.border="1px solid #050";
}
</script>
</head>
<body>
<form id="myForm" onsubmit="loadFunction()" method="POST">
<input type="text" id="op1" placeholder="operator 1" required></input> +
<input type="text" id="op2" placeholder="operator 2" required></input>
<button type="submit">show the result</button>
</form>
<div id="d1">
<h2>The summation will print here!!!</h2>
</div>
</body>
</html>

最佳答案

浏览器在您每次提交表单时执行的默认操作是进行这些重定向。你必须明确地关闭它。为此,添加一个 event.preventDefault(),如下所示:

<script>
function loadFunction(event){
//window.alert("hello");
var x= document.getElementById("d1");
var y =document.forms["myForm"]["op1"].value;
var z =document.forms["myForm"]["op2"].value;
x.innerHTML="<h2>" +(parseInt(y)+parseInt(z)) + "</h2>";
x.style.width="35%";
x.style.border="1px solid #050";

event.preventDefault();
}
</script>

关于javascript - 在javascript中提交表单后页面重定向回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com