使用ajax刷新<div>但传递计数器变量</div>

时间:2013-11-22 22:17:32

标签: javascript php jquery html ajax

我有两个.php个文件。第一个ajax_testing.php看起来像这样:

<!DOCTYPE html>
<html>
<?php
    $index_local=1;
    $_SESSION['global_index'] = $index_local;
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>

    <div id="main">Who is batman? click count=<?echo $_SESSION['global_index'] ?>
        <button id="detailed">LINK</button>
    </div>

</body>

<script type="text/javascript" language="javascript">
    $(document).ready(function() { /// Wait till page is loaded
        $("button").click(function(){

            <?php 
                $_SESSION['global_index']+=1;
            ?>
            $('#main').load('property-detailed.php?global_index='
                + <?php echo $_SESSION['global_index']; ?>
                + ' #main', function() {});
        });
    }); //// End of Wait till page is loaded
</script>
</html>

第二号文件名为property-detailed.php,如下所示:

<!DOCTYPE html>
<html>

<?php
    $_SESSION['global_index'] = $_GET['global_index'];
?>

<head>
<script></script>
</head>
<body>

    <div id="main">Who is batman? click count=<?php echo $_SESSION['global_index']; ?>
        <button id="detailed">LINK</button>
    </div>

</body>
<script type="text/javascript" language="javascript">
    $(document).ready(function() { /// Wait til page is loaded
        $("button").click(function(){

            <?php
                $_SESSION['global_index']+=1;
            ?>
            $('#main').load('property-detailed.php?global_index='
                + <?echo $_SESSION['global_index'] ?>
                + ' #main', function() {});
        });
    }); //// End of Wait till page is loaded
</script>
</html>

我加载了第一页,它有一个设置为1的变量$global_index和一个带有ajax命令的按钮,用第二页上的新信息重新加载div

我的目标是每次按下按钮时变量$global_index都会延续并递增。只有ajax被实现才有可能吗?如果是这样,有没有办法让它只在第一页发生?否则,让我的数据库跟踪这个数字并增加它会更容易吗?

1 个答案:

答案 0 :(得分:1)

ajax_testing.php

   <?php session_start(); ?>
    <script type="text/javascript" src="jquery.js"></script>
    <?php
    $_SESSION['counter'] = 1;
    $count = $_SESSION['counter'];


    ?>
    <div id="main">Batman<?php echo $count; ?></div>
    <button id="detailed">Link</button>

    <script type="text/javascript">
        $(document).ready(function(){
            $(document).on('click','#detailed',function(){
                var count = "<?php echo $count; ?>",
                    dataString = "counter=" + count;
                $.ajax({
                    type: "POST",
                    url: "property-detaild.php",
                    data:dataString,
                    success:function(data){
                        $('#main').html(data);
                        console.log(data);
                    }

                });
            })

        });
    </script>

在您的property-detailed.php

  <?php
   session_start();
   $_SESSION['counter'] = $_SESSION['counter']+1;
   echo $_SESSION['counter'];
  ?>