AJAX Jquery refreshing ALL content but I want NEW

2019-06-14 08:24发布

I may be reinventing the wheel but that's intentional. I am trying to make a real-time chat application using PHP HTML MySQL CSS. It's working quite well over the network and grabbing new content every second. In IE you can notice a flicker every second, seemingly it is pulling all that data again and again, even if there's no new content, and I don't like that.

Here is my refresh JS code:

 $(document).ready(function() {
     $("#data").load("data.php");
   var refreshId = setInterval(function() {
      $("#data").load('data.php');
   }, 1000);
   $.ajaxSetup({ cache: false });
});

data.php is just a while looping through all the database records and showing them:

    while ($row = mysql_fetch_array($result))
    {
    echo "<p><b>". $poster ."</b>: ". $message ."<br /><span style='font-size: 10px;'>". date('D d M - g:i:s a', strtotime($row['when'])) ."</span></p>";
    }

I've looked and looked on the internet for solutions, fading etc, I can't think of how to accomplish this, surely there is some nice and easy and efficient way?

3条回答
▲ chillily
2楼-- · 2019-06-14 08:38

The best solution, that I personally use in my shoutboxes, is to set a variable in the loaded data with a global variable.

Example:

<script type="text/javascript">
var global_var = 1234;
</script>
<p>HTML CONTENT GOES HERE</p>

Then when you call data.php you can call it with this new parameter.

$("#data").load('data.php?var=' + global_var );

Your global_var can be anything, from last inserted ID, or last timestamp, or???

查看更多
干净又极端
3楼-- · 2019-06-14 08:44

You should pass a time stamp to the server of the last update and only retrieve new content.

查看更多
相关推荐>>
4楼-- · 2019-06-14 08:53

This one is what you need, you only have to modify it for your needs:

Refresh a div's content only if new content is added to the database

This will pass the time when the page was loaded, and will refresh the data only if new content has been added, see the first answer.

All the best ;).

查看更多
登录 后发表回答