标签

时间:2018-01-21 21:17:29

标签: javascript php jquery ajax local-storage

我有一个服务器时间,当点击+时会增加,点击减去减少。我打开第一个标签,然后打开第二个标签。在第二个标签中,我改变时间(+或 - )。在第一个标签中,小时随机闪烁。我的错是什么?

的index.php

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<div id="timer"></div>
<button id="plus">+</button>
<button id="minus">-</button>

<script>
jQuery(document).ready(function ($) {
    var counter = 0;

    $('#plus').on('click', function (event) {
        counter++;
                localStorage.setItem('counter', counter);
        update();
    });

    $('#minus').on('click', function (event) {
        counter--;
                localStorage.setItem('counter', counter);
        update();
    });

    function update() {
        $.ajax({
            url: 'datetime.php',
            timeout: 1000,
            type: 'POST',
            data: 'counter=' + counter,
            success: function (response) {
                if (localStorage.getItem('response') !== null) { 
                    $('#timer').html(localStorage.getItem('response'));
                    localStorage.setItem('response', response);
                }       
                window.setTimeout(update, 1000);  
            }
        });
    }       
    update();
});
</script>

datetime.php

<?php 
$counter = $_POST['counter'] ?? 0;
echo date('d/m/Y h:i:s', time() + (int)$counter * 3600);

?>

2 个答案:

答案 0 :(得分:0)

第一个标签上的功能update未被调用,除非点击#plus#minus,并且因为它未被调用$('#timer').html()不会已经放置在axaj请求的成功回调中的工作。

你应该添加

$(function() {
  window.setTimeout(function() {
    update();
  },1000);
});

到更新#timer的网页,除非点击任何内容。

答案 1 :(得分:0)

  

在第一个标签中,小时随机闪烁。我的错是什么?

update()函数计划在window.setTimeout(update, 1000)重复调用。