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

标签 javascript ajax

我尝试使用 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/

相关文章:

javascript - 从头开始jQuery多文件上传

javascript - 如何在 Nextjs 上导出静态图片?

javascript - 为客户端搜索进行多参数过滤的优雅方法

javascript - 无法使用 vuetify 在 Vue js 中单击按钮来调用函数

jquery - Controller 的 Ajax 数据参数始终为空

javascript - 弹出模式仅适用于表中的第一个元素,第二次单击后不会再次打开

javascript - SignaturePad 未定义 - 无法将 signature_pad 模块初始化为脚本

javascript - ngRoute 和 Underscore.js 的 RequireJS shim 配置

javascript - 我如何使用 AJAX 将隐藏值提交给 php

php - 当新行添加到数据库时,Twitter 喜欢更新