[转]使用window.open替代window.ShowModalDialog,完成子页面和父页面之间的传值

使用window.ShowModalDialog可以完成子页面和父页面之间的传值,但是window.ShowModalDialog不是w3c的标准,有些浏览器不兼容,如Opera和一些低版本的浏览器,window.open是w3c标准写法,兼容性比window.ShowModalDialog要好,但window.open确没有window.ShowModalDialog对浏览器的阻塞式模式,在window.open代码执行完毕后,后面的代码就马上执行了,从而无法知道子窗口关闭时传递过来的值,经过1天的研究,终于实现了可以用window.open代替window.ShowModalDialog的方法,思路很简单,就是在子页面赋值完后先执行指定父页面的按钮事件再关闭,从而完成对子页面传递值的读取。代码分享出来,希望对遇到同样问题的有所帮助。

1.在父页面添加如下html代码

<input id="btnOpenCompleted" type="button" onclick="OpenCompleted()" value="OpenCompleted" style="display: none;" />

2.在父页面添加打开子窗口的javascript代码,窗口居中显示,如下:

function OpenChild(){

window.open('GetAllUser.aspx?controlName=btnOpenCompleted',null,'modal=yes,height=300,width=640,top='+(screen.height-400)/2+',left='+(screen.width-635)/2+',toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');

}

GetAllUser.aspx为要打开的子页面,controlName表示在子页面中完成赋值后,执行父页面中的按钮的id名称

3.btnOpenCompleted按钮点击执行的js代码,用于完成对子页面传递过来的值的读取

function OpenCompleted(){
    var returnValue= window.ReturnValue;//子页面传过来的值
    if(returnValue!="" && typeof returnValue!="undefined"){

      var value=returnValue.substring(returnValue.indexOf("[")+1,returnValue[i].lastIndexOf(']')); 

      ....

    }

 }

4.子页面关键代码

if (!IsPostBack)
{

  if (!string.IsNullOrEmpty(Request.QueryString["controlName"]))
      hfExecuteControl.Value = Request.QueryString["controlName"];

}
<asp:HiddenField ID="hfExecuteControl" runat="server" />//从父页面传过来的controlName=btnOpenCompleted,后台赋值读取

<input id="btnOk" type="button" value="确定" class="btn" onclick="ok()" />

function ok(){//选择
    window.returnValue="123123";
    if(window.opener!=null)
        window.opener.ReturnValue="123123";
        var parentControlName=document.getElementById("hfExecuteControl").value;
        if(parentControlName!=""){
              if(window.opener!=null)
                     window.opener.document.getElementById(parentControlName).click();
              else
                     window.parent.document.getElementById(parentControlName).click();
       }
       window.close();
}

父页面直接调用OpenChild()方法即可,对子页面传递过来的值在OpenCompleted()方法里面进行处理。

猜你喜欢

转载自blog.csdn.net/u012767263/article/details/46348297