jquery/ajax load new content when available

自古美人都是妖i 提交于 2019-11-30 21:16:14

问题


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?

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 :)


回答1:


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

Something along the lines of http://buntin.org/2008/09/23/jquery-polling-plugin/

Edit: This is untested.

AJAX call to 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);
        }
    }
?>

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



来源:https://stackoverflow.com/questions/2788975/jquery-ajax-load-new-content-when-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!