form表單提交的幾種方法


在form標簽中添加Action(提交的地址)和method(post),且有一個submit按鈕

<input type='submit'>

可以進行數據的提交,每一個input標簽都需要有一個name屬性,才能進行提交

 

當點擊登陸時,向數據庫發生的數據是:username=username&password=password.

這種默認的提交方式,一般會進行頁面的跳轉(不成功時跳轉到當前頁面)。而有時候我們是對彈出框進行數據提交的,希望提交成功則關閉彈出框並刷選父頁面,失敗則提示失敗原因,且彈出框不關閉。此時可以采用Ajax進行數據提交.

具體參考第四種方案:

一. 無刷新頁面提交表單

表單可實現無刷新頁面提交,無需頁面跳轉,如下,通過一個隱藏的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提交

表單可實現無刷新頁面提交,無需頁面跳轉,如下,通過一個隱藏的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>

三. js提交form表單

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

<form id="form" action="/url.do" method="post">
   <input type="text" name="name"/>
</form>
<script>
 
document.getElementById("form").submit();
 
jquery: $("#form").submit();
 
</script>

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

此時可以在callback函數中對請求結果進行判斷,然后執行不同的動作(頁面跳轉或刷選數據、提醒錯誤都可以)

五. 頁面無跳轉

如果通過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();
            }
        }
    }

 


免責聲明!

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



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