使用 PHP 打开模态窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14639235/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Opening a Modal Window "using" PHP
提问by Ryan Fitzgerald
I am creating a log in system in PHP and I'm trying to make it a little nicer.
我正在用 PHP 创建一个登录系统,我试图让它更好一点。
When you log out, you get redirected back to index.php. Like this:
当您注销时,您会被重定向回 index.php。像这样:
header("loaction: index.php?logout=true")
This makes the url look like www.mysite.com/index.php?logout=true. I then use the following code:
这使得 url 看起来像 www.mysite.com/index.php?logout=true。然后我使用以下代码:
if(isset($_GET['logout'])) {
$logoutvalue = $_GET['logout'];
if($logoutvalue = "true") {
$notification = "You've been logged out!";  
}
to get the value of logout from the URL and do something with it.
从 URL 中获取 logout 的值并对其进行处理。
I have a small popout window that will display the notification variable's value. In this case it's "You've been logged out!" My question is how do I get the modal window to display when the page loads and when the url equals /index.php?logout=true ?
我有一个小的弹出窗口,将显示通知变量的值。在这种情况下,它是“您已被注销!” 我的问题是如何在页面加载和 url 等于 /index.php?logout=true 时显示模式窗口?
All comments, answers, and suggestions are greatly appreciated!
非常感谢所有评论,答案和建议!
Thanks! - Ryan
谢谢!- 瑞安
回答by Class
Are you looking for something like:
您是否正在寻找类似的东西:
<script>
<?php if(isset($_GET['logout']) && $_GET['logout'] === 'true'){
    echo 'alert("You\'ve been logged out!");'
}
?>
</script>
EDIT: I believe you are looking for something like this for a modal window (using jQuery)
编辑:我相信您正在为模态窗口寻找这样的东西(使用 jQuery)
<?php if(isset($_GET['logout']) && $_GET['logout'] === 'true'){
    $message = "You've been logged out!";
?>
    <script>
    $(function() {
        $("#dialog").dialog();//if you want you can have a timeout to hide the window after x seconds
    });
    </script>
    <div id="dialog" title="Basic dialog">
        <p><?php echo $message;?></p>
    </div>
<?php } ?>
回答by Yang
First of all,
首先,
You can't "Open a Modal Window using PHP" directly. You can only do this only by exchanging variables (via JSON or XML), or embedding PHP conditions right into your markup.
您不能直接“使用 PHP 打开模态窗口”。您只能通过交换变量(通过 JSON 或 XML)或将 PHP 条件直接嵌入到您的标记中来执行此操作。
PHP and JavaScript are independent.
PHP 和 JavaScript 是独立的。
My question is how do I get the modal window to display when the page loads and when the url equals /index.php?logout=true ?
我的问题是如何在页面加载和 url 等于 /index.php?logout=true 时显示模式窗口?
There are two ways you can achieve this. 
First: Make a good use of embedding PHP conditions right into the markup.
有两种方法可以实现这一点。
第一:充分利用将 PHP 条件嵌入到标记中。
Second: Have somewhere hidden input, like (<input type="hidden" id="showModal" />) and then check if it exists via JavaScript itself.
第二:在某处隐藏输入,例如 ( <input type="hidden" id="showModal" />),然后通过 JavaScript 本身检查它是否存在。
For example:
例如:
<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
      window.onload = function(){
           if ( document.getElementById('showModal') ){
               alert('Box'); //replace with your own handler
           }
      }
   </script>
</head>
<body>
<?php if ( isset($_GET['logout']) && $_GET['logout'] === 'true' ): ?>
<input type="hidden" id="showModal" />
<?php endif;?>
</body>
</html>
回答by Amar Pratap
I know it is an old post, but to help someone in future with similar quest, I guess the following may help to get into right directions ( I have tested the below code myself, so please make adjustment).
我知道这是一个旧帖子,但为了帮助将来有类似任务的人,我想以下内容可能有助于进入正确的方向(我自己测试了以下代码,因此请进行调整)。
<?php if(isset($_GET['logout']) && $_GET['logout'] === 'true'){
        $message = "You've been logged out!";
    ?>
        <script>
        $(function() {
         $('#myModal').modal('show');
        });
        </script>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Edit Data</h4>
                </div>
                <div class="modal-body">
                    <div class="fetched-data"><?php $message ?></div> 
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <?php } ?>
回答by Thielicious
Best way to get done this by using the PRGpattern.
使用PRG模式完成此操作的最佳方法。
index.php
索引.php
1. Create the element for modal content in HTML
1. 在 HTML 中为模态内容创建元素
<div id=modal></div>
2. Style your #modalelement
2. 设计你的#modal元素
#modal {
    position: fixed;
    display: none; /*important*/
    color: white;
    text-align: center;
    z-index: 1000;
    width: 100%;
    height: 80px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: crimson;
    line-height: 2;
}
3. Define function how to show and disappear the modal box using jQuery
3.定义函数如何使用jQuery显示和消失模态框
'use strict'
window.jQuery ?
    $.fn.notify = function(interval) {      
        let el = $(this),
            text = el.text(),
            modal =()=> { // this will fire after the interval has expired
                el.fadeOut(),
                clearInterval(timer)
            },
            timer = setInterval(modal,interval)
        !text.match(/\S+/) || el.text('') // this will fire when modal box contains text    
            .append(`<h3>${text}</h3>`)
            .show()
    }
: alert('jQuery required.')
4. Attach .notify()to the jQuery selector
4.附加.notify()到jQuery选择器
$(()=>{
    $('#modal').notify(1500) // 1500 is the interval in milliseconds
})
5. Insert the notification sent from PHP inside the #modalelement
5.在#modal元素内插入PHP发送的通知
<div id=modal>
    <?=
        @$_SESSION["notify"]; // if this variable is not set, nothing will happen
        unset($_SESSION["notify"]); 
    ?>
</div>
6. Perform a simple $_GETrequest
6. 执行一个简单的$_GET请求
<a href=parse.php?logout>Logout</a>
parse.php
解析.php
7. Return a value using PHP in a $_SESSIONvariable
7. 在$_SESSION变量中使用 PHP 返回一个值
if (isset($_GET["logout"])) {
    $_SESSION["notify"] = "You have been logged out.";
    header("Location: index.php");
}
This is good practice. Once the logout request is sent to PHP, it will redirect to the index page with the result in a session variable. The PRG pattern does not always require a POST request. This example sends a GET request which is ok for logouts. Note that you have to place session_start();at the top of your files. 
这是一个很好的做法。一旦注销请求被发送到 PHP,它将重定向到索引页面,结果在一个会话变量中。PRG 模式并不总是需要 POST 请求。这个例子发送了一个可以注销的 GET 请求。请注意,您必须放置session_start();在文件的顶部。
回答by SimonB
Ok, so your existing code is like this snippet, and the problem you're having is that you want to show a jQuery/Bootstrap modal triggered by/with PHP, but jQuery/JS hasn't loaded yet (so you'll get a "$ undefined" error).
好的,所以你现有的代码就像这个片段,你遇到的问题是你想显示一个由/使用 PHP 触发的 jQuery/Bootstrap 模式,但 jQuery/JS 还没有加载(所以你会得到“$ 未定义”错误)。
When you say "a small popout window" I'm assuming you mean a bootstrap type modal.
当您说“一个小的弹出窗口”时,我假设您的意思是引导程序类型的模态。
if(isset($_GET['logout'])) {
  $logoutvalue = $_GET['logout'];
  if($logoutvalue = "true") {
    $notification = "You've been logged out!";  
  }
}
What I did was move the PHP code block to the end of the .php file, after jQuery (etc), and have an include, so it would look like this (assuming the name of your modal is id="logoutModal"):
我所做的是将 PHP 代码块移动到 .php 文件的末尾,在 jQuery(等)之后,并有一个包含,所以它看起来像这样(假设你的模态名称是 id="logoutModal"):
logout.php
登出.php
if(isset($_GET['logout'])) {
  $logoutvalue = $_GET['logout'];
  if($logoutvalue = "true") {
    include("logout-modal.php");  
  }
}
logout-modal.php
登出-modal.php
<?php ?>
  <script>
    $('#logoutModal').modal('show');
  </script>
<?php ?>
Not 100% sure this answers your question, but this works for me. Hope this helps.
不是 100% 确定这能回答你的问题,但这对我有用。希望这可以帮助。
回答by Bharath Parlapalli
Or you could even write the script inside if statement:
或者你甚至可以在 if 语句中编写脚本:
<?php
if(isset($_GET['logout']) && $_GET['logout'] === 'true'){ ?>
    <script type="text/javascript>
     window.open(yourhtml);
 </script>
</php } 
else {
// may be some other script
}
?>
回答by Kumar Saurabh Sinha
Please download a Modal JS Library http://simplemodal.plasm.it
请下载 Modal JS 库http://simplemodal.plasm.it
and Use the Condition
和使用条件
if(isset($_GET['logout'])) {
$logoutvalue = $_GET['logout'];
if($logoutvalue = "true") {
code to open the Modal as in the JS library..... 
}

