使用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()方法里面進行處理。

 

其它解決方案:

推薦使用layer.js

http://layer.layui.com/


免責聲明!

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



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