开发者

jQuery update div the moment a table is updated

I'm trying to figure out a way to have jQuery update a div the moment a table in mysql is updated. I've spent a vigorous amount of hours searching online for an answer, and so far, nothing. Can anyone help me out with 开发者_运维技巧this problem?


Well the steps you should probably take are:

Have a piece of AJAX code that queries the server for a change (like row count changing or something along those lines). Using jQuery you can do that:

function checkUpdates()
{
    $.ajax({
        type: "POST",
        url: 'hasDataChanged.php',   // a webservice or other URL that queries the database
        data: {},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            // return a JSON string like { "hasChanged" : "true" } or something
            if (data.hasChanged) {
                 // data has changed, do something
            }
        }
     });
}

Then you can use the Javascript method setInterval to call the code every few seconds. It is unrealistic to do it instantly.

$(document).ready(function() {
    setInterval("checkUpdates()", 3000);  // Calls the function every 3 seconds
});


You'll have to poll the database via ajax and php every (couple of) second(s) and check if the data has changed. if so, update the div.
i don't think there's a way of detecting the exact moment the db is updated.


Useful links on polling. It attempts to make server send data to browser:

  • http://onepixelahead.com/2010/04/30/html5-web-sockets-example/
  • http://en.wikipedia.org/wiki/Comet_(programming))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜