首页 > 解决方案 > 为什么我必须在这个聊天应用程序中不断触发 GET 请求?

问题描述

我是 AJAX 和 PHP 的新手,我不太明白这段代码:

https://github.com/Artifx/PHP-and-MySQL-Web-Development-5th-Edition/blob/master/Chapter23/client.js


var pollServer = function() {
    $.get('chat.php', function(result) {

        if(!result.success) {
            console.log("Error polling server for new messages!");
            return;
        }

        $.each(result.messages, function(idx) {

            var chatBubble;

            if(this.sent_by == 'self') {
                chatBubble = $('<div class="row bubble-sent pull-right">' + 
                               this.message + 
                               '</div><div class="clearfix"></div>');
            } else {
                chatBubble = $('<div class="row bubble-recv">' + 
                               this.message + 
                               '</div><div class="clearfix"></div>');
            }

            $('#chatPanel').append(chatBubble);
        });

        setTimeout(pollServer, 5000);
    });
}

$(document).on('ready', function() {
    pollServer();

    $('button').click(function() {
        $(this).toggleClass('active');
    });
});

$('#sendMessageBtn').on('click', function(event) {
    event.preventDefault();

    var message = $('#chatMessage').val();

    $.post('chat.php', {
        'message' : message
    }, function(result) {

        $('#sendMessageBtn').toggleClass('active');


        if(!result.success) {
            alert("There was an error sending your message");
        } else {
            console.log("Message sent!");
            $('#chatMessage').val('');
        }
    });

});

只有在发出 POST 请求后才能触发 GET 请求吗?这个逻辑有什么问题,需要pollServer每 5 秒运行一次函数?

标签: javascriptphpajax

解决方案


推荐阅读