带有id的div上的Ajax更新

时间:2012-08-05 10:13:31

标签: php javascript jquery html ajax

如何每x秒更新一次div id?我希望它更新其中包含的用户状态,其中包括对该帖子发表的评论数量的时间。

我已经尝试了setInterval但是要添加状态需要10秒钟,然后每隔x秒后重复一次状态。我只需要更新响应数据,而不是每隔10秒重新添加一条评论。

HTML:

<div id='divider-"+response['streamitem_id']+'></div>

JavaScript的:

$(document).ready(function(){
    $("form#myform").submit(function(event) {
        event.preventDefault();
        var content = $("#toid").val();
        var newmsg = $("#newmsg").val();

        $.ajax({
            type: "POST",
            url: "insert.php",
            cache: false,
            dataType: "json",
            data: { toid: content, newmsg: newmsg },
            success: function(response){ 
                $("#homestatusid").html("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'><a href='/profile.php?username="+response['username']+"'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><div style='cursor:pointer;position:relative;top:0px;float:right;padding-right:5px;' onclick=\"delete_('"+response['streamitem_id']+"');\">X</div><a href='/profile.php?username="+response['username']+"'>"+response['first']+" "+ response['middle']+" "+response['last']+"</a><span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+response['streamitem_timestamp']+"</a><hr>"+newmsg+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+response['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+response['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a id='likecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+response['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'>Like</div></a><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'></div></div><div id='streamdislike'><a id='dislikecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+response['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'>Dislike</div></a><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'></div></div></div><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+response['streamitem_id']+"'><div id='comment_list_"+response['streamitem_id']+"'><table width=100%><tr><td valign=top width=30px><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><td valign=top align=left><div class='stream_comment_inputarea'><input id='addcomment' type='text' name='content' style='width:100%;' class='input_comment' placeholder='Write a comment...'  onkeyup='growcommentinput(this);' autocomplete='off' onkeypress=\"if(event.keyCode==13){addcomment("+response['streamitem_id']+",this.value,'comment_list_"+response['streamitem_id']+"',"+response['id']+",'"+response['first']+" "+ response['middle']+" "+response['last']+"');this.value='';}\"><br/></div></div>");
            }
        });
        return false
    });
});

INSERT.PHP

$json = array();
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_id DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];


mysql_free_result($check1);

$check = "SELECT streamitem_timestamp FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_timestamp DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
mysql_free_result($check1);



$check = "SELECT username, id, first, middle, last FROM users";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];

mysql_free_result($check1);

echo json_encode($json);

4 个答案:

答案 0 :(得分:1)

您可以使用setIntervalsee Documentation)或setTimeoutsee Documentation)。

答案 1 :(得分:1)

首先在单执行函数中包装Ajax调用,回调函数引用相同的函数:

$(function() {
    (function ajaxcall() {
       $.ajax({
        url: 'foo.php',
        data: {boo:'moo',goo:'loo'},
        timeout: function() { ajaxcall(); },
        success: function(data) {
            //do somethng with the data
            //done, now call the function again:
            ajaxcall();
            }
        });
    }());
});

然后在PHP中编写如下内容:

$timeout = 30;
$pollinterval = .5;
$counter = 30;
while ($counter >= 0) {
//function which fetches fresh data and sets $test to true if data is returned
  list($test,$dataarray) = fetchdata();
  if ($test) { //JSON_encode the data array and send it
     echo JSON_ENCODE($dataarray);
     }
  else { //no fresh data, query the db again after wating for some time)
    usleep($pollinterval*1000);
    $counter -= $pollinterval;
  }
//timeout, return whetever you have!
echo JSON_ENCODE($dataarray);

答案 2 :(得分:0)

听起来像是民意调查。您可以包含一个AJAX调用,该调用将向后端PHP脚本发送请求,该脚本将搜索数据库以进行进一步更新。如果找到,它将立即返回新结果。接收新数据的客户端JS将在发出另一个请求之前等待30秒。如果PHP没有找到任何新数据,那么它将再次查询数据库,比如在5秒之后,并继续这样做,直到发生脚本定义的超时,例如25秒。然后它将返回一个空结果,在接收到客户端JS将立即发出另一个请求。

答案 3 :(得分:0)

我认为这是你想要的,使用Jquery:

HTML:

<div id="divider-whatever"></div>

Jquery的:

$(document).ready(function() {

    setInterval(function() {
        div = $("#divider-whatever");
        $.get(data.php, function(responseData) {
            div.html(responseData);
        }, 1000);
        // change 1000 to whatever time you need
        // change data.php to the file where your data is coming from
    });

});

*未经测试

希望这有帮助!