form表單提交帶參數的兩種方式

#第一種方式#

action寫明瞭LoginServlet,通過submit按鈕直接提交到後臺

<form action="LoginServlet" method="post">
    <input type="text" id="inputUsername" name="username" placeholder="Username" required autofocus>
    <input type="password" id="inputPassword" name="password" placeholder="Password" required>
    <button type="submit">登 錄</button>
</form>

後臺LoginServlet接收數據,注意前臺註明了是method=“post”,所以要在doPost()方法下寫

String username = request.getParameter("username");
String password = request.getParameter("password");

#第二種方式#

不希望直接提交,而是通過按鈕點擊手動提交,適用於需要傳入form之外的其他動態參數的時候

這裏寫了一個表單exportForm,爲了美觀,除了下載按鈕,另外兩個input設置成了不可見狀態,即隱藏狀態

<form id="exportForm" class="sel_btn" action="ExportExcelServlet" method="post" style="display: none">
     <input type="text" id="input_start" name="startdate" style="display:none">
     <input type="text" id="input_end" name="enddate" style="display:none">
     <input type="button" class="sel_btn" value="下載清單" onclick="ExportData()">
</form>

在ExportData()裏面再通過submit()提交 

function ExportData(){
    //傳參到form表單隱藏的input標籤裏面去
    $("#input_start").val(start);
    $("#input_end").val(end);

    //form表單提交
    document.getElementById("exportForm").submit();
}

後臺ExportExcelServlet獲取參數

String StartDate = request.getParameter("startdate");
String EndDate = request.getParameter("enddate");

#tips#

有以下兩個控件,分別是獲取起始日期和終止日期的輸入框

<input type="text" id="startDate" name="startDate">
<input type="text" id="endDate" name="endDate">

以下獲取控件值並對另一個控件進行賦值的兩種方式完全等價

document.getElementById("input_start").value = document.getElementById("startDate").value;
document.getElementById("input_end").value = document.getElementById("endDate").value;

$("#input_start").val(document.getElementById("startDate").value);
$("#input_end").val(document.getElementById("endDate").value);

 區別僅僅在於$.val()是JQuery的取值方式

document.getElementById("input_start").value;
$("#input_start").val()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章