刷新格,但前提是php文件的新内容 [英] Refresh div, but only if there is new content from php file

查看:181
本文介绍了刷新格,但前提是php文件的新内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景信息

我摆弄周围的一些PHP和AJAX的那一刻,尝试并获得了code工作自动刷新格(每10秒),包含注释。

I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.

下面是JavaScript的code我使用刷新DIV ..

Here is javascript code I am using to refresh the div..

<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
        $.ajaxSetup({ cache: false }); 
            setInterval(function() {
                    $('#content_main').load('/feed_main.php');
        }, 5000);  
});
// ]]></script>

在code将填充名为content_main的分区,这是在feed_main.php,基本上是访问数据库和回声的出最新评论...

The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...

问题

是否有可能,只加载分区content_main如果它里面的数据,并没有因为它加载的最后一次改变?

Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?

我的逻辑

由于我是比较新的JavaScript和Ajax我不太知道如何做到这一点,但我的逻辑是:

Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:

第一次运行时。

  • 从feed_main.php文件加载数据
  • 创建一个唯一的值(可能是一个哈希值?),以确定说,3个独特的评论

它运行每个其他时间...

Every other time it is run...

  • 在加载数据从feed_main.php文件
  • 创建一个新的独特的价值
  • 与previous一个
  • 检查该值
  • 如果它们是相同的,不刷新DIV,刚刚离开的事情,因为他们,但如果他们是不同的,然后刷新。

为什么我想这样做的原因是因为意见通常有图片连接,而且很讨厌看到的图像刷新每一次。

The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.

任何帮助,这将大大AP preciated。

Any help with this would be greatly appreciated.

推荐答案

我已经遇到了类似的问题,不是很久以前,我假设你使用MySQL或某事您的意见存储服务器端?

I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?

我解决我的问题,首先添加时间戳整数列到我的mysql表,然后当我增加了一个新的行,我只是简单地使用时间()保存当前的时间。

I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.

mysql的行插入,例如:

mysql row insert example:

$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";

第二步将是json_en $ C C你从服务器端发送数据$:

step two would be to json_encode the data you sending from serverside:

$output = array();

if ($html && $html !== '') {   // do we have any script output ?
  $output['payload'] = $html;  // your current script output would go in this variable
}
$output['time'] = time();      // so we know when did we last check for payload update

$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json;                    // send it to the client

所以,现在不是纯HTML,你的服务器端脚本返回是这样的:

So, now instead of pure html, your serverside script returns something like this:

{
  "payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
  "time":1354167493
}

您可以获取数据的JavaScript只是足够的:

You can grab the data in javascript simply enough:

<script type="text/javascript"> // <![CDATA[

var lastcheck;
var content_main = $('#content_main');

pollTimer = setInterval(function() {
  updateJson();
}, 10000);

function updateJson() {
  var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);

  $.ajax({
    url: request,
    dataType: 'json',
    async: false,
    cache: false,
    success: function(result) {
      if (result.payload) {        // new data
        lastcheck = result.time;   // update stored timestamp
        content_main.html(result.payload + content_main.html()); // update html element
      } else {                     // no new data, update only timestamp
        lastcheck = result.time;
      }
    }
  });
}

// ]]> </script>

这pretty的太多照顾通信服务器和客户端之间的,现在你只查询数据库是这样的:

that pretty much takes care of communication between server and client, now you just query your database something like this:

$timestamp = 0;
$where = '';

if (isset($_GET['timestamp'])) {
  $timestamp = your_arg_sanitizer($_GET['timestamp']);
}

if ($timestamp) {
  $where = ' WHERE timestamp >= '.$timestamp;
}

$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';

该时间戳获得通过来回,客户端始终发送由previous查询服务器返回的时间戳。

The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.

您的服务器只发送因为你选中最后一次提交评论,你可以prePEND他们到HTML的结尾像我一样。 (警告:我还没有添加任何一种理智控制的,你的意见可以得到非常长)

Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)

既然你轮询新的数据每隔10秒,你可能要考虑整个Ajax调用发送纯数据,以节省大量的带宽块(JSON字符串,它只是时间戳,只有大约20个字节)。

Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).

然后,您可以使用JavaScript生成HTML,它也有从服务器到客户端:)卸载大量工作的优势。您也将获得更精细的控制你要多少评论显示一次。

You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.

我做了一些相当大的假设,你将不得不修改code,以满足您的需求。如果你用我的code,和你的猫|电脑|房子发生爆炸,你把所有的作品:)

I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)

这篇关于刷新格,但前提是php文件的新内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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