我怎样才能使一个Ajax调用使用jQuery每一秒? [英] How can I make an ajax call using jQuery every second?

查看:112
本文介绍了我怎样才能使一个Ajax调用使用jQuery每一秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我设法让一切运行 - 最后一件事。基本上,人们的jQuery + AJAX功能添加了15秒的时间,并增加了一个新行到MySQL。我需要把一个新行,所以我可以得到历史的最后5行:

Okay, so I managed to get everything running - one last thing. Basically, one jQuery+ajax function adds 15 seconds to the date and adds a new row to MySQL. I need to put in a new row so I can get the last 5 rows for the history:

<?php 
include("inc/dblink.inc");
$itemid = intval($_POST['i']);
$bid = intval($_POST['b']);
$row = mysql_fetch_array(mysql_query("SELECT * FROM test WHERE itemid=$itemid ORDER BY bidid DESC LIMIT 0,1"));
$date = $row['date'];
$newdate = strtotime($date);
$newerdate = ($newdate + 15);
$newestdate = date("Y-m-d H:i:s", $newerdate);
mysql_query("INSERT INTO test (date,bid,itemid) VALUES ('$newestdate','$bid','$itemid')");
?>

第二个脚本刷新每一秒,并从表中显示的数据。

The second script refreshes every second and displays the data from the table.

<script type="text/javascript">
var auto_refresh = setInterval(
function()
{
$('#timeleft').load('gettime.php', { i: <?=$itemid;?> }).show();
$.ajax({
    type: "POST",
    url: "gettime.php",
    data: ({i : <?=$itemid;?>}),
    success: function(data){
        var s = data;
        var t = s.split(/[- :]/);
        var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
        $('#defaultCountdown').countdown({until: d,compact: true, 
        description: ''});
    }
});
}, 1000);
</script>

下面是gettime.php

Here's gettime.php

<?php 
include("inc/dblink.inc");
$itemid = intval($_POST['i']);
$row = mysql_fetch_array(mysql_query("SELECT * FROM test WHERE itemid='$itemid' ORDER BY bidid DESC LIMIT 0,1"));
$date = $row['date'];
echo $date;
?>

和我也用基思·伍德的jQuery的倒计时脚本发现的http://基思木。名称/ JS / jquery.countdown.js

And I also used Keith Wood's jQuery countdown script found in http://keith-wood.name/js/jquery.countdown.js

问题:

这行 $('#的timeleft)的负载('gettime.php',{我:??&LT; = $ itemid的;&GT;})。显示(); 还是不错的。新的时间与加入15秒示出了向上不会有问题。这是倒计时我在遇到问题。它不添加15秒计时器,但如果我刷新整个页面,我可以看到,有15秒的加入。

This line $('#timeleft').load('gettime.php', { i: <?=$itemid;?> }).show(); is good. The new time with 15 seconds added shows up without a problem. It's the countdown I'm having issues with. It doesn't add 15 seconds to the timer but if I refresh the whole page, I can see that 15 seconds was added.

我是什么做错了吗?相当新的使用jQuery。谢谢!

What am I doing wrong? Fairly new with jQuery. Thanks!

您可以看到它在这里行动

You can see it in action here.

推荐答案

有几个主要的问题在这里,还有一些次要的。

There's a couple of major issues here, and some minor ones.

这是非常简单的一个Unix时间戳,而不是格式化的日期工作。 PHP和JavaScript的是在这方面的非常相似。两者都基于相同的时代00:00 1月1日1970年UNIX / PHP在几秒钟内从该日起,并以毫秒为单位JavaScript的工作。因此,一个javascript 日期对象可以用新的日期(UNIX_TIMESTAMP * 1000)来初始化; 无需棘手的字符串处理

It's much simpler to work with a unix timestamp rather than a formatted date. PHP and javascript are very similar in this regard. Both are based on the same "epoch", 00:00 1 Jan 1970. UNIX/PHP work in seconds from that date and javascript works in milliseconds. Therefore a javascript Date object can be initialized with new Date(unix_timestamp * 1000); without the need for tricky string handling.

倒计时被设计为自由跑下来到零1秒的分辨率(再火一个可选的回调函数)。随着1秒的轮询间隔,它没有必要每次都重新初始化倒数计时器 - 只有当返回的时间被修改

Countdown is designed to free-run down to zero with a resolution of 1 second (then fire an optional callback function). With a poll interval of 1 second, it's not necessary to reinitialize the countdown timer every time - only when the returned timestamp has changed.

使用的setInterval ,它是亲切的客户端处理器创造尽可能多的对象/字符串尽可能一次外的setInterval 功能。这尤其适用于jQuery的陈述与(静态)选择,因为这些安排翻查了(可能很大)DOM。

With setinterval, it is kinder to client processors to create as many objects/strings as possible once outside the setinterval function. This particularly applies to jQuery statements with (static) selectors, as these cause the (potentially large) DOM to be searched.

把所有的在一起,我的JavaScript是这样的:

Putting all that together, my javascript would look like this:

$(function(){
    var $$ = {//cached jQuery objects
        timeleft: $('#timeleft'),
        defaultCountdown: $('#defaultCountdown')
    };
    var map_1 = {//namespace for setInterval and countdown data
        url: 'gettime.php',
        lastTimeStamp: 0,
        countdown_settings: {until:null, compact:true, description:''},
        itemid: <?=$itemid;?>
    };
    var auto_refresh = setInterval(function() {
        $$.timeleft.load(map_1.url, {i:map_1.itemid}).show();
        $.ajax({
            type: "POST",
            url: map_1.url,
            data: {i:map_1.itemid},
            success: function(unixTimeStamp) {
                unixTimeStamp = parseInt(unixTimeStamp);
                if(unixTimeStamp !== map_1.lastTimeStamp) {
                    map_1.countdown_settings.until = new Date(parseInt(unixTimeStamp) * 1000);
                    $$.defaultCountdown.countdown(map_1.countdown_settings);
                    map_1.lastTimeStamp = unixTimeStamp;
                }
            }
        });
    }, 1000);
});

当然,要完成这项工作,在PHP语句回声$日期; 将需要进行修改,以呼应日期的Unix时间戳重presentation。因为存储在数据库中这应该是相当琐碎的日期格式的知识。

Of course, to make this work, the PHP statement echo $date; will need to be modified to echo the unix timestamp representation of the date. That should be fairly trivial with knowledge of the date format as stored in the db.

编辑:Unix纪元是00:00(午夜)1970年1月1日,而不是12:00(中午),卫生署! JavaScript是在code一样的,所以没有任何负面影响。

这篇关于我怎样才能使一个Ajax调用使用jQuery每一秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆