如果Ajax返回成功,则使用jquery滚动到Div的底部

时间:2015-12-12 11:53:06

标签: javascript jquery html ajax autoscroll

我有这个Div,其中包含用户消息,其中最新消息位于Div的最底部,如果消息开始低于div高度,则启动滚动条:

  <div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">  
<div id="content"> 
    /// My messages
</div>
</div>

我在js文件夹中使用Jquery将滚动条带到Page load上的消息底部以显示最新消息:

var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);

这很有效,除非向页面添加新消息,否则滚动条不会再次自动向下滚动,除非您刷新页面或除非添加新消息。因此,每次收到新消息时都必须手动向下滚动。

我正在使用自动Div重新加载脚本来显示新消息:

<script>
setInterval(function() {
    $("#content").load(location.href+" #content","");
}, 5000);
</script>

我正在使用此Ajax脚本添加新回复:

<script> 
function loadDoc() {
  $.ajax({
            url: 'system/reply_system.php',
            type: 'POST',
            dataType: 'json',
            data: $('#reply').serialize(),
        })
        .done(function() {

            $.ajax({
                url: 'system/sars_system.php',
                type: 'POST',
                dataType: 'json',
                data: $('#reply').serialize(),
            })
            .done(function() {
                console.log("success");

            })
            .fail(function() {
                console.log("error");
            })

        })
        .fail(function() {
            console.log("error");
        })
}
</script> 

有没有一种方法可以设置Jquery在我的Ajax成功运行,以便滚动条将在新消息发送到底部,就像这样,我已经尝试过并发现它没有&#39工作:

    <script> 
    function loadDoc() {
      $.ajax({
                url: 'system/reply_system.php',
                type: 'POST',
                dataType: 'json',
                data: $('#reply').serialize(),
            })
            .done(function() {
              var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);

                $.ajax({
                    url: 'system/sars_system.php',
                    type: 'POST',
                    dataType: 'json',
                    data: $('#reply').serialize(),
                })
                .done(function() {
                    console.log("success");
                    var $content = jQuery(".list-group-message");
                    $content.scrollTop($content[0].scrollHeight);

                })
                .fail(function() {
                    console.log("error");
                })

            })
            .fail(function() {
                console.log("error");
            })
    }
    </script> 

根据要求包含其他代码:

<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">   

 <div id="content">                            



<?
$res6=mysqli_query($conn, "SELECT * FROM ap_messages WHERE conversation_id = '$conversation_id' ORDER BY time_sent ASC");
while($row6=mysqli_fetch_array($res6))
{   
 $me_message = $row6['message'];
 $me_message_id = $row6['message_id'];
 $me_sender_id = $row6['sender_id'];
 $todaysdate = date('d/m/Y');
 $me_time_sent_date = date('d/m/Y', strtotime($row6['time_sent']));
 $me_time_sent_date_and_time = date('d/m/Y H:i:s', strtotime($row6['time_sent']));
 $me_time_sent_time = date('H:i', strtotime($row6['time_sent']));
 if($todaysdate == $me_time_sent_date){
     $me_time = ''.$me_time_sent_time.'';
 } else {
    $me_time = ''.$me_time_sent_date.' '.$me_time_sent_time.''; 
 }


 $me_time_read = $row6['time_read'];
$res7=mysqli_query($conn, "SELECT * FROM ap_users WHERE user_id = '$me_sender_id'");
while($row7=mysqli_fetch_array($res7))
{   
 $me_first_name = $row7['first_name'];
 $me_last_name = $row7['last_name'];
  $me_display_img = $row7['display_img'];
}

mysqli_query($conn, "UPDATE ap_messages SET time_read = NOW() WHERE message_id = '{$me_message_id}' AND time_read = '0000-00-00 00:00:00' AND conversation_id = '$co_conversation_id' AND sender_id != '$user_id'");
?>  




<div class="media" style="max-width: <? echo $screenwidth; ?>px;">
  <div class="media-left">
    <a href="#">
      <img src="userimg/<? echo $me_display_img; ?>" alt="user" width="64px" height="64px" hspace="10px" class="media-object" align="left">
    </a>
  </div>
  <div class="media-body" style="position: relative !important;">
    <div style="display:inline"><b><a href=""><? echo ''.$me_first_name.' '.$me_last_name.''; ?></a></b></div> <div align="right" style="float:right; display:inline"> <? echo $me_time; ?> </div><br>
    <? echo $me_message; ?>
  </div>
</div>

<?
}
?>

</div>
</div>
<form action="" method="post" id="reply" name="reply" onsubmit="loadDoc()">
<div class="form-group">
 <textarea class="form-control" rows="3" cols="80" id="message" name="message" placeholder="Send a reply..."></textarea>
 <input type="hidden" id="conversation_id" name="conversation_id" value="<? echo $co_conversation_id; ?>">
 <input type="hidden" id="sarssystem" name="sarssystem" value="<? echo $sarssystem; ?>">
  <input type="hidden" id="user_id" name="user_id" value="<? echo $user_id; ?>">
</div>
<div class="form-group" align="right">

<div class="btn-group" align="left" style="float:left">
  <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <span class="glyphicon glyphicon-cog" aria-hidden="true"></span> <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="messages.php?convoid=<? echo $co_conversation_id; ?>&del=check">Delete Conversation</a></li>
    <li><a href="#">Visit Profile</a></li>
    <li><a href="#">Report User</a></li>
    <li role="separator" class="divider"></li>
    <li><a href="#">Change Display Photo</a></li>
  </ul>
</div>

  <button type="reset" class="btn btn-default btn-sm">Cancel</button>
  <button type="submit" class="btn btn-primary btn-sm">Send Message</button>
</div>

<script>
setInterval(function() {
    $("#content").load(location.href+" #content","");
}, 5000);
</script>



 <script> 
function loadDoc() {
 $.ajax({
  url: 'system/reply_system.php',
  type: 'POST',
  dataType: 'json',
  data: $('#reply').serialize(),
  success: function(data) {

    console.log("success");
    var $content = $(".list-group-message");
    $content[0].scrollTop = $content[0].scrollHeight;

    // Second ajax
    $.ajax({
      url: 'system/sars_system.php',
      type: 'POST',
      dataType: 'json',
      data: $('#reply').serialize(),
      success: function(data) {
        $content[0].scrollTop = $content[0].scrollHeight;
      },
      error: function(e) {
         //called when there is an error
         console.log('fail');
      }
    });

  },
  error: function(e) {
    //called when there is an error
    console.log('fail');
  }
});
}
</script> 



                        </div>

3 个答案:

答案 0 :(得分:1)

脚本完成后,您可以使用以下脚本:

$content[0].scrollTop = $content[0].scrollHeight;

示例:

$.ajax({
  url: 'system/reply_system.php',
  type: 'POST',
  dataType: 'json',
  data: $('#reply').serialize(),
  success: function(data) {

    console.log("success");
    var $content = $(".list-group-message");

    $content.text(data); // Here you have to insert the received data.
    $content[0].scrollTop = $content[0].scrollHeight;

    // Second ajax
    $.ajax({
      url: 'system/sars_system.php',
      type: 'POST',
      dataType: 'json',
      data: $('#reply').serialize(),
      success: function(data) {
        $content.text(data); // Here you have to insert the received data.
        $content[0].scrollTop = $content[0].scrollHeight;
      },
      error: function(e) {
         //called when there is an error
         console.log('fail');
      }
    });

  },
  error: function(e) {
    //called when there is an error
    console.log('fail');
  }
});

希望它有所帮助。

答案 1 :(得分:1)

试试这样:

$.ajax({
    url: 'system/sars_system.php',
    type: 'POST',
    dataType: 'json',
    data: $('#reply').serialize(),
    }),
    success: function(response) {
        console.log(response);
        var $content = $(".list-group-message");
        $content[0].scrollTop = $content[0].scrollHeight;
    },
    error: function(response) {
        console.log(response);
    }
});

答案 2 :(得分:0)

这是我所采用的方法。首先访问要加载数据的父div。然后使用jquery向下滚动。

$.ajax({
        type: "GET",
        url: baseURL + "notification/get_load_notif_member_message",
        data: "member_id=" + member_id + "&message_id=" + message_id,
        contentType: 'html',
        success: function (html) {
            $('.msg_history').html(html);
            $("input[name='text']").val('');
            var $content = $(".msg_history");
            $content[0].scrollTop = $content[0].scrollHeight;
        },
        error: function (html) {
            $('.msg_history').html('Something went wrong. Please try again.');
        }
    });