1

我创建了一个聊天功能。在这里,如果我写了一些东西,它就会显示在聊天 div 上。但我的问题是,如果我再写一次,那么第二条消息会替换为第一条消息。我想在聊天 div 上显示所有消息。喜欢聊天

测试.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dhuronto</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
 $('#message').keydown(function (e){
    if(e.keyCode == 13 ){
if($(this).val()!=0)
    {
    e.preventDefault();//use this to prevent default behavior
    calculate();
    }
   }
   });
});

function calculate()
{
$.post(
"test_1.php",
$('#message').serialize(),
function(response)
{
$("#chat").html(response);
});
$('#message').val("");
}



</script>
</head>
    <body>
    <div id="chat" style=" width: 300px; height: 500px; border: 1px solid black; overflow: auto">

        </div>
        <textarea id="message" name="chat_message"></textarea>
    </body>
</html>

test_1.php

<?php

$message=$_POST['chat_message'];

echo "$message";

?>
4

3 回答 3

2

改为使用appendhtml替换所有内容。

$.post("test_1.php", $('#message').serialize(), function(response) {
    $("#chat").append($message.val() + '<br/>')
              .scrollTop($('#chat')[0].scrollHeight);
});

您可以在每条消息后添加换行符,这将在新行中。
并用于scrollTop在输入新消息后向下滚动。

演示

于 2012-12-20T04:11:55.177 回答
1

html替换内容,你想要append. 改变:

$("#chat").html(response);

到:

$("#chat").append(response);
于 2012-12-20T04:11:40.157 回答
0

代替

$("#chat").html(response);

您可以使用

$("#chat").append(response);

jquery html 是替换整个 html 和 jquery append 是添加其他 html 标记或 html 值

于 2012-12-20T04:13:00.877 回答