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

时间:2015-01-11 10:10:17

标签: javascript jquery ajax

上下文

我正在尝试创建我的聊天应用程序,以便在收到新消息时仅滚动到底部,我尝试使用此问题中提到的解决方案(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成功时都会调用scroll函数,但这只是每隔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);    

1 个答案:

答案 0 :(得分:0)

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

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

上述内容就是您所需要的。