如何让window.open()以post请求方式调用(巧妙解法)

问题由来:

在公司遇到一个线上bug,如下

var url = 'http://106.75.31.215:8012/onlinePreview?url=' + encodeURIComponent(fileUrl);

window.open(url, "_blank", "height=" + winHeight
            + ",top=80,left=80,toolbar=no, menubar=no, scrollbars=yes, resizable=yes");

由于 fileUrl 是多张图片的 url 拼装而来,在这里我们使用get请求方式调的后台图片预览接口,发现后台报错 请求头过长。

特此查了下  

在IE8 下的URL地址总长度为:4076,超过该长度会自动忽略后面的内容;

在firefox 25下的URL地址总长度可以达到:7530,超过该长度会访问错误;

在chrome 29.0.1547.62 的最大总长度达到:7675,超过该长度会访问错误;

尴尬。。。我们这有一万多的字符。

解决思路:

换post请求啊,不能忍啊,因为post请求理论上没有请求数据的长度限制,但是没这么搞过啊。

解决方案:

好像以前只在form表单里接触过post调用,那么能不能让window.open()先打开一个隐藏的form表单呢?然后把请求数据塞进去,而偷偷的自动提交,不久可以了么。机智啊

实施如下:

var winHeight = window.document.documentElement.clientHeight-10;
var url = 'http://106.75.31.215:8012/picturesPreview';
var formStr = '<form style="visibility:hidden;" method="POST" action="' + url + '">' + '<input type="hidden" name="urls" value="' + encodeURIComponent(urls) + '" />' + '<input type="hidden" name="currentUrl" value="' + encodeURIComponent(fileUrl) + '" />'+ '</form>';
var win = window.open("", "_blank", "height=" + winHeight + ",top=80,left=80,toolbar=no, menubar=no, scrollbars=yes, resizable=yes"); win.document.body.innerHTML = formStr; win.document.forms[0].submit();

经测试,可以跑通,完美解决。 

原文地址:https://www.cnblogs.com/xinde123/p/8528777.html