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>
              
相關文章
相關標籤/搜索