使用MySQL和PHP进行JQuery轮询.如何?

问题描述:

在网站上,我发现了各种方法来对MySQL进行好坏评估,并且大多数情况下都使用了2年.

I have found various ways to poll MySQL on the site both good and bad and mostly 2 years old.

我想看一个如何正确轮询服务器的示例.

I would like to see an example of how to properly poll a server.

我有一个MySQL表,其中插入了注释.我想在JQuery中看到一个有关如何轮询此服务器并附加到DIV的示例,仅是自上次轮询检查以来在表中插入的新注释,而不是每5秒显示最后10个条目.

I have a MySQL table where comments are inserted. I'd like to see an example in JQuery on how to poll this server and append to a DIV, only the new comments inserted in a table since the last polling check instead of displaying the last 10 entries every 5 seconds.

一个非setInterval的例子将是理想的,因为我读过setInterval不在乎在发出另一个请求之前请求是否成功.

A non setInterval example would be ideal as I've read setInterval does not care if request was successful before making another request.

您将必须向服务器端脚本发送AJAX请求,该脚本将检查数据库中的新注释并以JSON编码返回它们.

You would have to send a AJAX request to a server side script that would check for new comments in the DB and return them JSON encoded.

要仅获取最新的注释,请在客户端代码上维护上一次获取注释的时间戳.下次您请求评论时,请传递此时间戳.您的服务器端脚本将仅返回带有时间戳字符的注释,而不是传入的参数.

To get only the latest comments, on the client side code, maintain a timestamp of the last comment fetch. Next time you request comments, pass this timestamp. Your server side script will only return comments with a timestamp grater than the passed in paramter.

您可以在成功处理程序中重新提交AJAX请求,而不必使用setInterval.

Instead of using setInterval, you can resubmit the AJAX request in the success handler.

function ajaxRequest(timestamp) {
    $.ajax({
        url : 'url_to_post?timestamp=' + timestamp,
        success : function(response){
            //handle the new comments here
            //call this function again
            //sleep for 3 seconds first
            setTimeout(function(){
                timestamp += 3000;
                ajaxRequest(timestamp);
            },3000);

        }

    });
}