博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

利用window.open实现post方式的参数传递

Posted on 2011-05-06 13:24  sigo-yr  阅读(1190)  评论(0编辑  收藏  举报

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

示例代码如下:

View Code
/*这里可以传递多个参数*/
function openPostWindow(id, content) {
var tempForm = document.createElement("form");
tempForm.id
= "tempForm1";
tempForm.method
= "post";
tempForm.target
= "newPage";
tempForm.action
= "*******.aspx"; //在此处设置你要跳转的url

var hiddInput_id = document.createElement("input");
hiddInput_id.type
= "hidden";
hiddInput_id.name
= "OrderId";
hiddInput_id.value
= id;
tempForm.appendChild(hiddInput_id);

var hiddInput_content = document.createElement("input");
hiddInput_content.type
= "hidden";
hiddInput_content.name
= "Content";
hiddInput_content.value
= encodeURIComponent(content);
tempForm.appendChild(hiddInput_content);

tempForm.attachEvent(
"onsubmit", function () { openWindow(); });
document.body.appendChild(tempForm);
tempForm.fireEvent(
"onsubmit");
//将form的target设置成和windows.open()的name参数一样的值,通过浏览器自动识别实现了将内容post到新窗口中
tempForm.submit();
document.body.removeChild(tempForm);
}

function openWindow() {
var sunwin = window.open('about:blank', "newPage", 'height=720px, width=720px, top=50, left=300, toolbar=no, menubar=no, scrollbars=yes, location=no, status=yes');
sunwin.focus();
}

流量统计