form表單提交方式


無刷新頁面提交表單

表單可實現無刷新頁面提交,無需頁面跳轉,如下,通過一個隱藏的iframe實現,form表單的target設置為iframe的name名稱,
form提交目標位當前頁面iframe則不會刷新頁面

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

通過type=submit提交

一般表單提交通過type=submit實現,input type="submit",瀏覽器顯示為button按鈕,通過點擊這個按鈕提交表單數據跳轉到/url.do

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

js提交form表單

js事件觸發表單提交,通過button、鏈接等觸發事件,js調用submit()方法提交表單數據,jquery通過submit()方法

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

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

 

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){
      }
   });
              

頁面無跳轉

如果通過form表單提交請求服務端去下載文件,這時當前頁面不會發生跳轉,服務端返回void,通過response 去寫文件數據,
頁面會顯示下載文件。

<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();
            }
        }
    }
              

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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM