简体   繁体   English

如何防止我的页面在提交时刷新

[英]How do I prevent my page from refreshing on submit

Here is the JavaScript:这是 JavaScript:

myform.addEventListener('submit', (event) => {
fetch("url", {mode: "no-cors"})
.then(res=> {
    if(res.ok){
        console.log("cats")
    }
    else{
        event.preventDefault()
        document.getElementById("subcim_error_message").innerHTML="You must add a title!"
        return false
    }
})})

Here is the html:这是html:

   <head>
    <title>pH Login</title>
    <link rel="stylesheet" href="../styles/ph-styles.css"/>
</head>
<body>
    <header>
        <h1>parry Hotter School for Alchemy and Pyromancy</h1>
    </header>
    <div id="hat" style="display: flex; justify-content: center;">
        <img src="https://www.renderhub.com/realityscanning/old-boot-with-plants-inside/old-boot-with-plants-inside-01.jpg" style="height: 15rem" alt="Sorting Boot"/>
    </div>
    <span class="error_form" id="subcim_error_message"></span>
    <form name="myform">
        <section class="two_columns">
            <label for="username">Username:</label>
            <input id="username" placeholder="parry Hotter" type="text"/>
            <label for="password">Password:</label>
            <input id="password" placeholder="*******" type="password" maxlength="20"/>
        </section>
        <input type="submit"/>
    </form>
    <footer>
        <h6>&copy;Copyright pHSfAaP. All rights reserved.</h6>
    </footer>
    <style>
        #hat{
            margin: 3em;
        }

        img{
            border: 1em;
            border-style: solid;
            border-color: steelblue;
        }
    </style>
    <script src="../scripts/parry-hotter-login.js"></script>
</body>

I am trying to display an error message when someone enters invalid credentials but everytime it happens the page refreshes so the error message immediately vanishes我试图在有人输入无效凭据时显示错误消息,但每次发生时页面都会刷新,因此错误消息立即消失

Literally by adding client site validation .实际上是通过添加客户端站点验证 As per the MDN:根据 MDN:

Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format.在向服务器提交数据之前,确保以正确的格式填写所有必需的表单控件非常重要。 This is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls.这称为客户端表单验证,有助于确保提交的数据符合各种表单控件中规定的要求。 This article leads you through basic concepts and examples of client-side form validation.本文将引导您了解客户端表单验证的基本概念和示例。

Then there's server side validation of course.当然还有服务器端验证。 For that you could setup focus or keypress event handlers to validate input and add some UI hints, eg, messages, colors, checkmarks, and toggle the submit button state.为此,您可以设置焦点或按键事件处理程序来验证输入并添加一些 UI 提示,例如消息、颜色、复选标记和切换提交按钮状态。

UPDATE更新

Here's a snippet that adds the required attribute to the inputs (client-side validation) and a handler for the submit event (server-side validation).这是一个将required属性添加到输入(客户端验证)和提交事件处理程序(服务器端验证)的片段。 The trick to cancelling submission of a form is for the onsubmit handler to return false .取消提交表单的技巧是让onsubmit处理程序返回false

 document.getElementById('myform').onsubmit = function() { // mock response res = { status: "failed", reason: "the user name does not exist." }; if (res.status !== "ok") { alert(res.reason); return false; } return true; }
 <head> <title>pH Login</title> <link rel="stylesheet" href="../styles/ph-styles.css"/> </head> <body> <header> <h1>parry Hotter School for Alchemy and Pyromancy</h1> </header> <div id="hat" style="display: flex; justify-content: center;"> <img src="https://www.renderhub.com/realityscanning/old-boot-with-plants-inside/old-boot-with-plants-inside-01.jpg" style="height: 15rem" alt="Sorting Boot"/> </div> <span class="error_form" id="subcim_error_message"></span> <form id="myform"> <section class="two_columns"> <label for="username">Username:</label> <input id="username" placeholder="parry Hotter" type="text" required/> <label for="password">Password:</label> <input id="password" placeholder="*******" type="password" maxlength="20" required/> </section> <input type="submit"/> </form> <footer> <h6>&copy;Copyright pHSfAaP. All rights reserved.</h6> </footer> <style> #hat{ margin: 3em; } img{ border: 1em; border-style: solid; border-color: steelblue; } </style> <script src="../scripts/parry-hotter-login.js"></script> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM