即使在页面刷新时,ajax聊天界面也不显示消息

时间:2017-08-28 20:03:00

标签: javascript php jquery html ajax

我有这个javascript文件应该通过ajax机制从PHP文件中获取消息,即使消息被成功发送,屏幕上也没有显示任何内容,但它在PHP文件中,并且它也在数据库中。任何人都可以指出我正在制造的任何错误,是否有另一种方式来建立聊天界面?这是javascript文件和HTML的代码

>>> [[tup[0], ', '.join(d for d in set(tup[1].split(', ')))] for tup in mylist]
[[20, 'August 2013, September 2015, September 2016'], [30, 'August 2012']]
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('');
        }
    });
    
});

我也有CSS,我认为不会影响任何输出:

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么你就错了:

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

如果成功进入日志文件,您将返回消息, 我想如果你这样做就足够了:

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

我建议您在此时创建此div:

<div class="container">

    <div id='returning_div_id' class='alert alert-success'></div>

    <div class="panel panel-default">