在不使用触发按钮的情况下在 PHP 中显示 bootstrap 模态

Displaying a bootstrap modal in PHP without using a trigger button

我想通过检查 PHP 会话是否存在来显示模态,代码如下:

<?php if(isset($_SESSION['login'])) { ?>
    <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
    <p>Body</p>
    </div>
    <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
    </div>
    </div>
    <script>$("#myModal").modal("show");</script>
<?php } ?>

这不起作用。

我之前也提到过类似的问题,但他们没有给出明确的picture.Please帮助。

首先,我建议将 .js 文件与 .php 文件分开 因为 - 有时 - 我还需要 运行 php 在我的 js 文件中编码,这是我喜欢做的一点 "trick":

js 文件的扩展名应为 .php(以便触发 php 解释器),因此文件名可能类似于:scripts.js.php。在这里,我还假设您调用了主文件,例如:index.php.

现在,让我们来烤蛋糕吧:

index.php 文件的示例:

<html>
<head>
    <!-- here include your head elements and styling -->
    <link href="path/to/bootstrap.css" rel="stylesheet">
    <link href="path/to/other.css" rel="stylesheet">
</head>
<body>
<!-- here goes the body code -->
    <!-- my practice is to include the modal code and scripts at the end of the file -->
        <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
        </div>
        <div class="modal-body">
        <p>Body</p>
        </div>
        <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
        </div>
        </div>

    <?php 
        $show_modal="";
        if(isset($_SESSION["login"])){$show_modal="1";}else{$show_modal="0";}
        include("scripts.js.php"); 
    ?>
    </body>
    </html>

这是我对 scripts.js.php 文件的建议:

<script src="path/to/jquery.js"></script>
<script src="path/to/bootstrap.js"></script>
<script src="path/to/otherfile.js"></script>
<script>
$(document).ready(function(){
    var showModal = '<?php echo $show_modal; ?>';
    if(showModal=="1"){$("#myModal").modal("show");}
});
</script>

这是一个对我一直有效的解决方案...希望它对你也有效!