在PHP中显示引导模式而不使用触发器按钮

时间:2016-04-02 09:58:27

标签: php jquery twitter-bootstrap bootstrap-modal

我想通过检查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 } ?>

这不起作用。

我也提到了以前类似的问题,但他们没有给出清晰的图片。请帮助。

1 个答案:

答案 0 :(得分:0)

首先,我建议将.js文件与.php分开 因为 - 有时候 - 我还需要在我的js文件中运行php代码,这是我喜欢的一点“技巧”:

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>

这是一个永远适合我的解决方案......希望它也适合你!

相关问题