仅当收到 Ajax 请求的字符串消息时,才滚动到底部

Only scroll to bottom when a message a string is received for an Ajax request

本文关键字:消息 滚动 底部 Ajax 请求 字符串      更新时间:2023-09-26

>上下文

我正在尝试制作我的聊天应用程序,以便它仅在收到新消息时滚动到底部,我已经尝试使用此问题中提到的解决方案(JQuery 聊天应用程序仅在新消息上滚动到div 底部?),但它不起作用。 我还看到了另外两个问题,但是代码比我认为需要的要复杂得多。

我的代码

var scroll = function() {
    function getMessages(letter) {
        var div = $("#chat");
        div.scrollTop(div.prop('scrollHeight'));
    }
    $(function() {
        getMessages();
    });
}
var newmessages = function() {
    setTimeout(newmessages, 5000);
    var request = $.ajax({
        url: "ajaxtesting.php",
        type: "GET",
        dataType: "html"
    });
    request.done(function(msg) {
        $("#chat").html(msg);
        scroll();
    });
    request.fail(function(jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}
newmessages();

如您所见,每次 Ajax 成功时都会调用滚动函数,但是,它只是每 5 秒滚动到底部。我尝试使用字符串长度没有取得多大成功,因为我得到了奇怪的字符串长度,即使没有发送消息,也会不断变化。

服务器端代码

     require_once('mysqli_connect.php');
     //$id = $_SESSION["user_id"]; 
     //$cid = $_SESSION["cid"];
     $id = $_SESSION['user_id'];
     $cid = $_SESSION['cid'];
     $query = "SELECT text, sentuser, recieveuser, icebreaker 
     FROM convoreply  WHERE cid = $cid ORDER BY senttime ASC";
     $response = @mysqli_query($dbc, $query);
     if($response){
     while($row = mysqli_fetch_array($response)){ 
     $sentuser = $row['sentuser'];                       
     $text = $row['text']; 
     $recieveuser = $row['recieveuser'];  
     $icebreaker = $row['icebreaker'];      
     if ($sentuser == $id){    
     echo '<div class="bubble">',"<p>", $text,"<br/>'n","</p>",'</div>';  
     }
     if ($recieveuser == $id) {    
     echo '<div class="bubble2">',"<p>", $text,"<br/>'n","</p>",'</div>'; 
      }
      if ($icebreaker == 1) {    
     echo '<div class="bubble3">',"<p>", $text,"<br/>'n","</p>",'</div>'; 
     }
     if ($sentuser == 10000){
     echo '<div class="bubble3">',"<p>", $text,"<br/>'n","</p>",'</div>'; 
     }
     }}
     if ($cid == 0){
     echo '<p>Please click on a user on the left hand 
     side to view the conversation.</p>';
      }

      mysqli_close($dbc);    

因为您绑定了ajax.done承诺,所以无论是否有任何新消息,都会执行此承诺。

request.done(function(msg) {
    if(msg !== null && msg !== "") {
        $("#chat").html(msg);   
        scroll();
    }
});

您需要的就是上述内容。