如何使用ajax从服务器获取时间?

时间:2011-07-14 13:54:56

标签: php ajax

我正在尝试创建一个像便士拍卖这样的网站如何显示倒数时间? 我尝试使用ajax,但有时它吞下一两秒,它显示像10,9,7,6,3秒...我的意思是它没有显示正确的倒数时间..请帮我解决这个问题

这是我的代码

<?php 
@session_start();
include "includes/common.php";
include_once "includes/classes/class.Auction.php";
$objAuction     = new Auction();
$result=$objAuction -> getStatus();
echo $result;

&GT;

// ajax代码

function getStatusOne(pId)

{

var strURL="get_status_one.php?pId="+pId;
var req = getXMLHTTP();

if (req) 
{           
    req.onreadystatechange = function() 
    {
        if (req.readyState == 4) 
        {   
            if (req.status == 200) 
            {       
                  //alert(req.responseText);
                var result= req.responseText.substr(1).split("|");

                for (var x = 0; x < result.length; x++)
                {

                    var resultN=result[x].split(",");

                    var prId=resultN[0];

                    var temp=resultN[1];
                    var sec=parseInt(temp);


                    var price=resultN[2];
                    //alert(prId+' '+temp+' '+price);
                    var mem=resultN[3];
                    var img=resultN[4];
                    var autobid=resultN[5];
                    if(img=='') {
                        img='images/profile/no_image.jpg'
                    }
                    if(!price)
                    {
                        price='0.00';
                    }
                    if(!mem)
                    {
                        mem='No Bidders Yet';
                    }

                    if(document.getElementById("bid_price"+prId))
                    {   

                        document.getElementById("bid_price"+prId).innerHTML='$'+price;
                        document.getElementById("bidder_name"+prId).innerHTML=mem;
                        document.getElementById("userimg").src=img;
                        document.getElementById("bid_rate").innerHtml=autobid;

                         if(sec<= -1)
                        {

                                sold(prId);
                                if(document.getElementById('end'+pId))
                                {
                                    document.getElementById('end'+pId).style.display="block";
                                }
                                if(document.getElementById('div_bid_image'))
                                {
                                    document.getElementById('div_bid_image').style.display="none";
                                }   
                                if(document.getElementById('clsBidB'+pId))
                                {                                       
                                    document.getElementById('clsBidB'+pId).style.display="none";    
                                }
                        } 
                        else {
                            if(document.getElementById('div_bid_image').style.display == "none")
                            {
                                document.getElementById('div_bid_image').style.display="block";
                            }
                            if(sec >=0)
                            {
                                SetCountdownText(sec,"div_timer"+prId,prId);
                            }
                        }
                    }
                }

            } 
            else 
            {
                //alert("There was a problem while using XMLHTTP:\n" + req.statusText);
            }               
        }
    }       
    req.open("POST", strURL, true);

    req.send(null);
}

}

//用于计算时间的PHP代码

    function getStatus()
{

    $selProd="select a.pdt_id, unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."') as seconds, b.bid_price,c.uname  from tbl_products a left join tbl_auction b on a.pdt_id=b.product_id left join tbl_members c on  b.member_id=c.member_id where(select unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."'))>= 0 ";

    if($this->ExecuteQuery($selProd,"norows") > 0)
    { 

        $auctionArr=$this->ExecuteQuery($selProd,"select");

        $auctionName=$this->array2str($auctionArr);
    }
    return $auctionName;
}

function array2str($array,$level=1) 
{
    $str = array();
    foreach($array as $key=>$value) {
     if(is_int($key))
     {
        $nkey = $key;
        $nvalue = is_array($value)?'|'.$this->array2str( $value ) : $value;
        $str[] = $nvalue;
    }
    }       
     return implode(',',$str);

}

4 个答案:

答案 0 :(得分:1)

试试这个

<?php

$target = mktime(0, 0, 0, 14, 07, 2011) ;

$today = time () ;

$difference =($target-$today) ;

$days =(int) ($difference/86400) ;

print "Our event will occur in $days days";

?>

答案 1 :(得分:1)

假设您有类似ID为“倒计时”的DIV(显示倒计时):

示例JavaScript(假设使用jQuery - 推荐):

(function(jQuery) {
    updateCountdown("countdown"); // Call on page load
    var countdown = setInterval('updateCountdown("countdown")', 1000); // Update countdown every second
})(jQuery);

function updateCountdown(elementId) {
    jQuery.ajax({       
        url: "/ajax/countdown.php?auctionId=123", 
        type: "GET",
        dataType: "json",
        success: function(response) {
            // Insert value into target element
            jQuery("#"+elementId).html(response["timeRemaining"]);

            // Stop countdown when complete
            if (response["countdownComplete"] == true)
            clearInterval(countdown);
        }
    });
}

示例PHP脚本(假设在上面的JavaScript中位于/ajax/countdown.php):

<? php
/* Insert your own logic here */
$response["timeRemaining"] = "5 seconds";
$response["countdownComplete"] = false; // Set to true when countdown complete
echo json_encode(response);
?>

我建议使用所有计算服务器端(在PHP中),因为它具有非常出色的时间/日期处理(具有许多内置方法)并且需要较少的代码来实现整体。

答案 2 :(得分:0)

有一个PHP页面回显倒计时时间。然后在该页面上使用类似jQuery的AJAX HTTP Request,并在某个地方填充DOM元素中的响应。

答案 3 :(得分:0)

为什么需要Ajax来显示倒计时时间?为什么不能在页面加载其他数据时显示它?