项目总结15:JavaScript模拟表单提交(实现window.location.href-POST提交数据效果)

时间:2023-03-09 04:22:49
项目总结15:JavaScript模拟表单提交(实现window.location.href-POST提交数据效果)

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-源码示例

 function downloadInfoToExcel(){
var utl = "XXXX";
var idsStr = "xxxx"; document.write("<form action='"+url+"' method='post' name='form' content-type= 'application/json' style='display:none'>");  
document.write("<input type='hidden' name='idsStr' value='"+idsStr+"'>");  
document.write("</form>");  
document.form.submit();
}

  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