利用window.open實現post方式的參數傳遞

來源:互聯網
上載者:User
    最近在做web項目,碰到需要跨頁面傳遞參數的功能,就是那種需要把當前頁面的內容帶到新開的子表單中,以前的做法是傳一個id過去,然後在新視窗中去讀資料庫的內容。雖然不怎麼麻煩,但是如果內容麼有在資料庫裡儲存,僅僅是處以擬稿狀態時,就不能實現了,使用者還常常認為是個bug。考慮採用get的方式傳遞,把需要的內容都序列化然後,通過url去傳,顯得很臃腫,而且get的傳遞內容長度有限制。於是就想到用post的方式傳遞,問題在於open方法不能佈建要求方式,一般網頁的post都是通過form來實現的。如果僅僅類比form的提交方式,那麼open方法裡那種可設定表單內容的參數又不能用。最後想辦法整了這麼一個兩者結合的方式,將form的target設定成和open的name參數一樣的值,通過瀏覽器自動識別實現了將內容post到新視窗中。
    比較有意思的是直接通過調用form的submit方法不能觸發onsubmit事件,查看了協助文檔,必須手動的觸發,否則只能看到頁面重新整理而沒有開啟新視窗。代碼中只傳遞了一個參數內容,實際可傳遞多個。
具體代碼如下:openPostWindow
 1 function openPostWindow(url, data, name)  
 2      {  
 3          var tempForm = document.createElement("form");  
 4          tempForm.id="tempForm1";  
 5          tempForm.method="post";  
 6          tempForm.action=url;  
 7          tempForm.target=name;  
 8          
 9          var hideInput = document.createElement("input");  
10          hideInput.type="hidden";  
11          hideInput.name= "content"
12          hideInput.value= data;
13          tempForm.appendChild(hideInput);   
14          tempForm.attachEvent("onsubmit",function(){ openWindow(name); });
15          document.body.appendChild(tempForm);  
16          
17          tempForm.fireEvent("onsubmit");
18          tempForm.submit();
19          document.body.removeChild(tempForm);
20     }
21     
22      function openWindow(name)  
23      {  
24          window.open('about:blank',name,'height=400, width=400, top=0, left=0, toolbar=yes, menubar=yes, scrollbars=yes, resizable=yes,location=yes, status=yes');   
25      }  
26     </script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.