24.form表单提交的六种方式

form表单提交方式

1.无刷新页面提交表单

表单可实现无刷新页面提交,无需页面跳转,以下,经过一个隐藏的iframe实现,form表单的target设置为iframe的name名称,
form提交目标位当前页面iframe则不会刷新页面jquery

<form action="/url.do" method="post" target="targetIfr">
<input type="text" name="name"/>
</form>   
<iframe name="targetIfr" style="display:none"></iframe> 
              

2.经过type=submit提交

通常表单提交经过type=submit实现,input type="submit",浏览器显示为button按钮,经过点击这个按钮提交表单数据跳转到/url.doajax

<form action="/url.do" method="post">
   <input type="text" name="name"/>
   <input type="submit" value="提交">
</form>
              

3.js提交form表单

js事件触发表单提交,经过button、连接等触发事件,js调用submit()方法提交表单数据,jquery经过submit()方法json

<form id="form" action="/url.do" method="post">
   <input type="text" name="name"/>
</form>
              

js: document.getElementById("form").submit();
jquery: $("#form").submit();浏览器

4.ajax异步提交表单数据

采用ajax异步方式,经过js获取form中全部input、select等组件的值,将这些值组成Json格式,经过异步的方式与服务器端进行交互,
通常将表单数据传送给服务器端,服务器端处理数据并返回结果信息等服务器

<form id="form"  method="post">
   <input type="text" name="name" id="name"/>
</form>
  var params = {"name", $("#name").val()}
 $.ajax({
      type: "POST",
      url: "/url.do",
      data: params,
      dataType : "json",
      success: function(respMsg){
      }
   });
              

5.页面无跳转

若是经过form表单提交请求服务端去下载文件,这时当前页面不会发生跳转,服务端返回void,经过response 去写文件数据,
页面会显示下载文件。app

<form action="/url.do" method="post">
   <input type="text" name="name"/>
   <input type="submit" value="提交">
</form>

@RequestMapping(value = "/url")
    public void exportFile(HttpServletRequest req, HttpServletResponse response, String rptId)
            throws Exception {
        OutputStream out = null;
        try {
            String rptName = "file";
            String fileName = new String((rptName + excelAble.getFileSuffix()).getBytes("GBK"),
                    "8859_1");
            response.reset();
            response.setContentType("application/octec-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            out = response.getOutputStream();
            excelAble.exportFile(out);
        } catch (Exception e) {
            logger.error(e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
              

6.form表单上传文件

使用form表单进行上传文件须要为form添加enctype="multipart/form-data" 属性,除此以外还须要将表单的提交方法改为post,
以下 method="post", input type的类型须要设置为file异步

 <form action="/url.do" enctype="multipart/form-data" method="post">
     <input type="file" name="name"/>
     <input type="submit" value="提交">
   </form>
              
相关文章
相关标签/搜索