jquery/ajax 在可用时加载新内容 [英] jquery/ajax load new content when available

查看:19
本文介绍了jquery/ajax 在可用时加载新内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个相当含糊的问题——抱歉.如果我有一个在 PHP 和 MySQL 上运行的用户输入和提交数据的论坛、聊天框或类似的东西,那么在提交新提交的内容时,让所有用户在页面上自动显示新提交的内容的最佳方法是什么?

I know this is quite a vague question -- sorry about that. If I have a forum, shoutbox or something similar where users enter and submit data, running on PHP and MySQL, what is the best way to have the newly submitted content automatically display on the page for all users when it is submitted?

很像实时新闻提要,如果您喜欢的话...效果有点像在 stackoverflow 上起作用,当您回答问题时,您会在提交新答案时收到通知.我想测试新提交的内容,然后自动显示.

Much like a live newsfeed, if you like... The effect sort-of works here at stackoverflow, when you are answering a question you are told when new answer is submitted. I want to test for newly submitted content and then display it automatically.

有什么建议吗?非常感谢:)

Any suggestions? Many thanks :)

推荐答案

显然,人们首先想到的是每 x 秒发出一次轻量级 AJAX 请求,以检查新内容.

Obviously the first thing that springs to mind is a lightweight AJAX request every x seconds to check for new content.

类似于 http://buntin.org/2008/09/23/jquery-polling-plugin/

这是未经测试的.

AJAX 调用 http://example.com?lastCheck=1273244156

PHP: 
<?
    if(isset($_GET['lastCheck'])){
        $ts = mysql_real_escape_string($_GET['lastCheck']);

        $result = mysql_query("SELECT * FROM `table` WHERE `timestamp` >= {$ts}");
        $rows = mysql_fetch_array($result, MYSQL_ASSOC);

        if($rows){
            header('Cache-Control: no-cache, must-revalidate');
            header('Content-type: application/json');
            echo json_encode($rows);
        }
    }
?>

然后使用 jQuery 检查 AJAX 响应是否是有效的 JSON,如果是,则构建您的项目并将它们附加到您的容器中.

Then use jQuery to check if the AJAX response is valid JSON, if so build your items and append them to your container.

这篇关于jquery/ajax 在可用时加载新内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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