Ajax发表评论,如StackOverflow

HeX*_*HeX 6 php ajax jquery

我的问题是,什么是更好的方式来做StackOverflow上的评论系统,我的意思是我从我的浏览器发送请求,每个人都会看到这个评论(或在其他浏览器中)没有刷新页面像一些聊天.

我的解决方案是使用setInterval,但我认为必须有另一种方式

$(document).ready(function() {
get();
$('#send').click(function() {
    $.post('http://localhost/mvc.com/comment/post', {
        n_id: parseInt(newsId),
        user_id: $('#uid').val(),
        text: $('#content').val(),
        token: $('#token').val()
    }, function (ret) {
        if (ret.comm.err) {
            $('.f').empty().prepend('<li id=e><h3 style="color: red">ERROR</h3></li>');
            return false;
        }
        get();
    });
    setInterval(get,3000);
});

$('#content').keypress(function(e){
    var key = e.which;
    var cnt=$(this).val().length;
    var max=100;
    var tot=parseInt(max-cnt);
    if(key >= 33 || key == 13 || key == 32) {
        if (parseInt(tot) <= 0) {
            e.preventDefault();
        }
    }
});

function get() {
    $.post('http://localhost/mvc.com/comment', {get: parseInt(newsId)}, function (ret) {
        $('.f').empty();
        for (var key in ret.comm) {
            $('.f').append('<li class=c id=' + ret.comm[key].id +
            '><span>' + ret.comm[key].name + '</span><hr><br>' + ret.comm[key].text + '</li>');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Nom*_*man 4

虽然我已经看到您的上述方法被用于实时更新,但这不是正确的方法。

您将需要使用 Web 套接字,这是实时 Web 应用程序的事实。

Web 套接字本身就是一个主题,我可以继续讨论,但这里有一个链接可以帮助您开始了解它们: http: //socketo.me