如何讓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();

經測試,可以跑通,完美解決。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM