JavaScript模擬表單提交(實現window.location.href-POST提交數據效果)
前沿
1-在具體項目開發中,用window.location.href方法下載文件,因window.location.href默認GET方法,如果跟在URL后面的參數過長,則會請求失敗;
2-而window.location.href並沒有POST方法可用,
3-只能通過JavaScript模擬表單提交,從而實現window.location.href-POST提交數據下效果,以下提供兩種方法
正文
方法1:DOM方法
1-源碼示例
1 function downloadInfoToExcel(){ 2 var utl = "XXXX"; 3 var idsStr = "xxxx"; 4 5 document.write("<form action='"+url+"' method='post' name='form' content-type= 'application/json' style='display:none'>"); 6 document.write("<input type='hidden' name='idsStr' value='"+idsStr+"'>"); 7 document.write("</form>"); 8 document.form.submit(); 9 }
2-關於document.write()方法
1.因為 document.write 寫入文檔流,在關閉(已加載)的文檔上調用 document.write 會自動調用 document.open,這將清除該文檔。
2.向一個已經加載,並且沒有調用過document.open()的文檔寫入數據時,會自動完成調用document.open()的操作。一旦完成了數據寫入,系統要求調用document.close(),以告訴瀏覽器頁面已經加載完畢。寫入的數據會被解析到文檔結構模型里。在上面的例子里,元素h1會成為文檔中的一個節點。
3.如果document.write()被直接嵌入到HTML主體代碼中,那么它將不會調用document.open()。
4.連續連個document.write()也不會相互覆蓋 是因為document.write("A")結束后,默認是不會調用document.close()的,所以第二個document.write("B")不會覆蓋前一個write的內容,而是進行追加。
5.我們可以手動調用document.close()方法,關閉由document.open()方法創建的文檔流,但是我們無法關閉系統創建的文檔流
方法2:Jquery方法
1-源碼示例
function downloadInfoToExcel(){ var utl = "XXXX"; var idsStr = "xxxx"; var $form=$(document.createElement('form')).css({'display':'none'}).attr("method","POST").attr("action",url); var $input=$(document.createElement('input')).attr('type','hidden').attr('name','idsStr').val(idsStr); $form.append($input); $("body").append($form); $form.submit(); }
參考資料
1-https://blog.csdn.net/Jzsn_Paul/article/details/80025683
2-https://blog.csdn.net/mf_mofy/article/details/78997002