开发者

Live updates using JQuery?

开发者 https://www.devze.com 2022-12-13 19:18 出处:网络
At the moment, I have a Javascript (JQuery) front-end which periodically makes requests to a seperate, PHP script which returns posts.

At the moment, I have a Javascript (JQuery) front-end which periodically makes requests to a seperate, PHP script which returns posts.

For the sake of efficiency, however, I'd like to simply add new results to the array, not even looking at existing posts.

As it stands, I've attempted to do so with times (i.e. "SELECT * FROM table WHERE time >= $time"), however, have realized its limitations and inability to conform with my initial idea.

Are there any ideas out there? I'd much prefer to do this without 开发者_如何学编程having to reform my scripts into using XML to transfer the data - however, if such is the only case, I'll be happy to oblige. :)


Your question is lacking detail on a number of things. I am going to assume that you are periodically going to make a call to a PHP script. I will assume the the posts table has an auto increment ID. That way you can pass that to a query and get newer posts.

var current_id = 1234; // this will need to be filled in somehow

setInterval(get_latest_posts, 10000);

function get_latest_posts() {
  $.getJSON('/latest', {current_id: current_id}, function(data) {
    current_id = data.new_id;
    // process data.posts
  });
}

PHP script:

<?php
mysql_connect(...);
mysql_select_db('...');

// retrieve newer posts
$current_id = intval($_POST['current_id']);
$sql = <<<END
SELECT * FROM posts WHERE id > $current_id
END;
$query = mysql_query($sql);
$new_id = $current_id;
$posts = array();
while ($row = mysql_fetch_array($query)) {
  $posts[] = $row;
  $new_id = max($new_id, $row['id']);
}

// return the posts as a JSON object    
header('Content-Type: application/json');
echo json_encode(array(
  'new_id' => $new_id,
  'posts' => $posts,
));
?>

There are many variations on this theme.


If your HTML looked something like this (You will need to adjust it to your situation):

<div id="posts">
  <div id="post-1"> ... </div>
  <div id="post-2"> ... </div>
  <div id="post-3"> ... </div>
  <div id="post-4"> ... </div>
</div>

You could update your load request like this:

function loadNewPosts(){
   var id = $("#posts > div:last")[0].id.substr(4);

   $.get('/update.php', { lastId: id }, function(data){
       $("#posts").append(data);
   }, 'html');
}

window.setInterval(loadNewPosts, 1000*60*5) // every 5 minutes

And just look for new posts with an id that is greater than the last id on the page, and return the new ones as HTML.

Update If your posts are in reverse chronological order, use :first instead of :last and prepend() instead of append()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号