只有在收到 Ajax 请求的消息字符串时才滚动到底部

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

上下文

我正在尝试使我的聊天应用程序只在收到新消息时滚动到底部,我尝试使用此问题中提到的解决方案 (JQuery chat application scroll to bottom of div ONLY on new message?),但它没有工作。我还看到了另外两个问题,但是代码比我认为需要的要复杂得多。

我的代码

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();
    }
});

像上面这样的东西就是你需要的。