zoukankan      html  css  js  c++  java
  • form表单自动提交

           form表单提交是web项目中经常遇到的,但是如果form中只有一个input为text类型的输入框时,

       需要格外注意,因为这时候只要你按下回车键,form表单就会自动提交,这是form表单的一个特性。

       如何有效的防止呢?

       小编认为最简洁有效的方法就是增加一个隐藏域。比如下面的代码就可以解决问题:  

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    <form action="../index/login.do" method="post" >
       <label for="files">用户名:</label>
       <input type="text" name="userName">
       <input type="text" style="display: none;">
      <button type="submit">提交</button>
    </form>
    </body>
    </body>
    </html>

     但是这也有个bug就是如果input框获取了焦点,但是未输入任何字符的情况下,点击回车键依旧可以提交表单。因此接下来的这种方法则规避了这一个BUG


    第二种方案,就是在input为text的文本框中,增加onkeydown事件,并且当按键是回车键也就是keyCode=13时,不做处理,代码如下:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    <form action="../index/login.do" method="post">
       <label for="files">用户名:</label>
       <input type="text" name="userName" onkeydown="if(event.keyCode==13){return false}">
    <!--    <input type="text" style="display: none;"> -->
      <button type="submit">提交</button>
    </form>
    </body>
    </body>
    </html>

                                                    以上是小编在实际过程中测试的代码,如有问题,欢迎留言交流!

  • 相关阅读:
    [Github]在仓库中添加Sponsor赞助者按钮
    SpringMVC面试题常问的29道(附答案)
    Spring常问面试题及答案汇总(2020版)
    Java面试题及答案整理(2020最新版)
    MySQL数据库下载及安装教程(最新版!史上最详细!)
    +0与-0在plc传递数值上的坑
    halcon极坐标转换与亮暗缺陷检测结合的案例(转)
    互联网项目管理
    zabbix 监控IO DISK
    转 更改当前schema
  • 原文地址:https://www.cnblogs.com/ljy-20180122/p/9211366.html
Copyright © 2011-2022 走看看