验证表单内容之后如何阻止表单提交

一般我们在表单提交的时候,如果有错误信息,我们就会阻止表单的提交,一般是弹出一个警告框,但是在点击确认之后,表单还是提交给数据库了。这里用一个简单的script脚本方法来解决。

表单代码内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script type="text/javascript">
//检测表单提交的正确性
    function check(){
        var name = document.getElementById("username");
        if (name.value=="") {
            alert("用户名不能为空!");
            name.focus();
            return false;
        }
        return true;
    }
</script>
</head>
<body>
    <form action="pengjun.html" method="get">  <!-- 表单以post的方式提交给pengjun.html -->
        姓名:<input type="text" name="username" id="username">
        密码:<input type="text" name="pwd">
        <input type="submit" value="提交" onclick="return check();"> <!--  在这里调用js函数,并且获取函数里面返回的值,利用return -->
    </form>
</body>
</html>    

pengjun.html 页面的代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
    欢迎注册!!!!!!!
</body>
</html>
原文地址:https://www.cnblogs.com/xs-yqz/p/5126553.html