[英]page redirect back after form submit in javascript
I was trying to add the two operator using javascript and then I wished to try it in ajax then I wanted to see the difference between two codes action but whenever I implemented the addition in javascript I got stuck because thepage show the result for a sec then it redirect back.我试图使用 javascript 添加两个运算符,然后我想在 ajax 中尝试它,然后我想查看两个代码操作之间的区别,但是每当我在 javascript 中实现添加时,我就卡住了,因为页面显示结果一秒钟它重定向回来。 Can anyone please tell me what is the wrong with this code?
谁能告诉我这段代码有什么问题?
<!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>
The default action that browser performs each time you submit the form is to make those redirections.每次提交表单时浏览器执行的默认操作是进行这些重定向。 You have to explicitly turn this off.
您必须明确关闭此功能。 To do that add a
event.preventDefault()
, like this:为此,添加一个
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>
The other possibility is to return false
in onsubmit like that:另一种可能性是在 onsubmit 中
return false
,如下所示:
<script>
function loadFunction(){
//...
return false;
}
</script>
and和
<form id="myForm" onsubmit="return loadFunction()" method="POST">
You can then control if form should be submitted by returning either true
or false
from loadFunction()
.然后,您可以通过从
loadFunction()
返回true
或false
来控制是否应提交表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.