window.open以post方式提交

来源:互联网 发布:linux创建文件目录 编辑:程序博客网 时间:2024/05/22 11:39

第一种方式

   在web项目中,碰到需要跨页面传递参数的功能,就是那种需要把当前页面的内容带到新开的子窗体中,以前的做法是传一个id过去,然后在新窗口中去读数据库的内容。虽然不怎么麻烦,但是如果内容么有在数据库里保存,仅仅是处以拟稿状态时,就不能实现了,用户还常常认为是个bug。考虑采用get的方式传递,把需要的内容都序列化然后,通过url去传,显得很臃肿,而且get的传递内容长度有限制。于是就想到用post的方式传递,问题在于open方法不能设置请求方式,一般网页的post都是通过form来实现的。如果仅仅模拟form的提交方式,那么open方法里那种可设置窗体属性的参数又不能用。最后想办法整了这么一个两者结合的方式,将form的target设置成和open的name参数一样的值,通过浏览器自动识别实现了将内容post到新窗口中。
    比较有意思的是直接通过调用form的submit方法不能触发onsubmit事件,查看了帮助文档,必须手动的触发,否则只能看到页面刷新而没有打开新窗口。代码中只传递了一个参数内容,实际可传递多个。
具体代码如下:

代码 

[html] view plaincopy
  1. function openPostWindow(url, data, name)    
  2.   {    
  3.      var tempForm = document.createElement("form");    
  4.   
  5.      tempForm.id="tempForm1";    
  6.   
  7.      tempForm.method="post";    
  8.   
  9.      tempForm.action=url;    
  10.   
  11.      tempForm.target=name;    
  12.   
  13.     
  14.   
  15.      var hideInput = document.createElement("input");    
  16.   
  17.      hideInput.type="hidden";    
  18.   
  19.      hideInput.name"content"  
  20.   
  21.      hideInput.valuedata;  
  22.   
  23.      tempForm.appendChild(hideInput);     
  24.   
  25.      tempForm.attachEvent("onsubmit",function(){ openWindow(name); });  
  26.   
  27.      document.body.appendChild(tempForm);    
  28.   
  29.   
  30.   
  31.      tempForm.fireEvent("onsubmit");  
  32.   
  33.      tempForm.submit();  
  34.   
  35.      document.body.removeChild(tempForm);  
  36.   
  37. }  
  38.   
  39.   
  40.   
  41. function openWindow(name)    
  42.   
  43. {    
  44. window.open('about:blank',name,'height=400width=400top=0left=0toolbar=yesmenubar=yesscrollbars=yesresizable=yes,location=yesstatus=yes');  
  45. }    

第二种方式

代码 
[html] view plaincopy
  1. function openWindowWithPost(url,name,keys,values)  
  2. {  
  3.     var newWindow = window.open(url, name);  
  4.     if (!newWindow)  
  5.         return false;  
  6.           
  7.     var html = "";  
  8.     html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";  
  9.     if (keys && values)  
  10.     {  
  11.        html += "<input type='hidden' name='" + keys + "' value='" + values + "'/>";  
  12.     }  
  13.       
  14.     html += "</form><script type='text/javascript'>document.getElementById('formid').submit();";  
  15.     html += "<\/script></body></html>".toString().replace(/^.+?\*|\\(?=\/)|\*.+?$/gi, "");   
  16.     newWindow.document.write(html);  
  17.       
  18.     return newWindow;  
  19. }  

推荐使用第一种方式,第二种方式测试过程中发现,与日历弹出框冲突,如果子页面上有日历弹出框,则点日历框会不停刷新页面,不会弹出日历框。当然,也可能是我用的日历框的问题。

0 0