轉載自:http://www.884358.com/php-layer/php
在開發中常常會遇到點擊按鈕彈出展現表單,在表單中填寫信息後,點擊保存,最後返回列表頁的狀況。css
咱們想實現的比較友好的效果一般是:用戶點擊按鈕彈出子窗口,填寫完子窗口中的表單信息後,點擊子窗口中的保存按鈕,頁面提示保存成功,並關閉子窗口,最後刷新父頁面。html
爲了更加優雅的彈出子窗口,咱們使用了layer這一款優秀的jQuery插件。在使用過程當中,能夠很方便的彈出咱們想要的頁面,例如表單填寫頁面。
例如以下頁面:jquery
<!DOCTYPE html> <html lang="en"> <head> <title> 彈窗測試 </title> <meta charset="utf-8"/> <script src="https://cdn.bootcss.com/jquery/2.0.2/jquery.min.js"></script> <script src="https://cdn.bootcss.com/layer/3.0.1/layer.min.js"></script> </head> <body> <button id="parentIframe">點擊彈出窗口</button> </body> </html> <script> function refresh() { location.reload(); } //彈出一個iframe層 $('#parentIframe').on('click', function () { layer.open({ type: 2, title: '點擊彈出窗口', maxmin: true, shadeClose: true, //點擊遮罩關閉層 area: ['800px', '520px'], content: 'http://127.0.0.1/test/layer/form.php' }); }); </script>
點擊「點擊彈出窗口」按鈕,頁面會彈出子窗口顯示http://127.0.0.1/test/layer/f...的頁面內容,form.php的代碼以下:post
<?php if ($_POST) { //處理你的業務... echo "<script>parent.parent.layer.closeAll();parent.parent.layer.msg('添加成功,頁面正在刷新');parent.parent.setTimeout('refresh()',2000);</script>"; die; } ?> <!DOCTYPE html> <html lang="en"> <head> <title> 彈窗測試 </title> <meta charset="utf-8"/> </head> <body> <iframe name="iframe" id="iframe" style="display:none"></iframe> <form action="#" method="post" target="iframe"> <table border="1"> <tr> <td>姓名</td> <td><input type="text" name="username"/></td> </tr> <tr> <td>年齡</td> <td><input type="text" name="age"/></td> </tr> <tr> <td colspan='2'><input type="submit" value="提交"/> </td> </tr> </table> </form> </body> </html>
注意表單form的target屬性是指向的本頁面的iframe,target的名稱即爲iframe的name。當填寫了表單上的信息後,點擊提交按鈕,頁面會將form表單中的信息提交到iframe中,因爲iframe沒有指定src屬性,因此iframe的地址是頁面本身,同時設置了display:none,因此是不可見的(爲了便於觀察效果,你也能夠暫時先把display:none刪除)。因此等同於表單提交到頁面自身,只不過是展現在了自身的iframe裏。自身的php代碼裏識別到了post過來的數據,則會輸出一句js代碼,js代碼的目的是關閉頂級父窗口的layer彈出窗,並在頂層父窗口中顯示提示信息,最後讓頂級父頁面在兩秒鐘後刷新本身。測試