在某些情況下,我們需要以 POST 方式提交表單,主要有兩個原因:一是請求的參數過長,超過了 GET 允許的最大長度;二是想要隱藏網址列中的參數。此時就可以透過 JS 模擬 POST 提交來實現。
//新創建一個form表單 document.write('<form name=myForm></form>'); var myForm=document.forms['myForm']; myForm.action='runEmpAttendance'; myForm.method='POST'; var input = document.createElement('input'); input.type = 'text'; input.name = 'userId'; input.value = 100; myForm.appendChild(input); myForm.submit(); //使用jsp中已經存在的form表單,添加其他的參數 var myForm = document.forms['listEmployee']; //表單的name var input = document.createElement('input'); input.type = 'hidden'; input.name = 'currentPage'; input.value = 1; myForm.appendChild(input); myForm.method= 'POST'; myForm.submit();
以上示範了兩種常見做法:一是動態建立一個全新的 form 表單並填入參數後提交;二是在頁面既有的表單上動態追加隱藏欄位,再設定為 POST 方式提交。兩者都能有效隱藏網址列中的參數,讓資料傳輸更安全、更清爽。