我的JavaScript AJAX有什么问题?

时间:2015-12-01 14:07:19

标签: javascript php jquery ajax chat

我正在尝试创建一个简单的聊天系统,在新消息存在时加载新消息。以前,我只是加载了数据库中的所有消息。当新用户发送消息时,我需要滚动条滚动到底部。

使用此方法完成了聊天加载,但我无法滚动,因为它会每200毫秒到达底部。

$(document).ready(function(e) {
    $.ajaxSetup({cache:false});
    setInterval(function() {$('#chatlog').load('logs.php');
    var chatReload = document.getElementById("chatlog");  //This is the scrolling part
    chatReload.scrollTop = chatReload.scrollHeight;  ////This is the scrolling part 
    }, 200); //AJAX updates 200ms
});

新的JavaScript代码加载以前的消息。但是在刷新页面之前不会加载任何新消息。刷新页面后,消息全部加载,但不会再次加载任何新消息。为什么这不起作用?感谢。

HTML和JavaScript:

        <div id="tab3">
          <h2>Chat Room</h>

                <div id="c-input_wrap">
                    <div id="chatlog">
                        Loading chat please wait...
                    </div>

                <div id="chatwrap">
                    <div id="chatinput">
                    <form name="chatbox" class="userchat">
                        <input class="userchat" name="message" type="text" autocomplete="off" onkeydown="if (event.keyCode == 13) document.getElementById('chatbutton').click()" autofocus/><br>
                        <input class="userchat" id="chatbutton" name="submitmsg" type="button" onclick="submitChat()" value="Send" />
                    </form>
                    </div>
                </div>
            </div>
        </div>

<script>    
    var form = document.querySelector('form[name="chatbox"]');
    form.addEventListener("submit", function (event) {
        event.preventDefault();
    });

    function submitChat() {
        if(chatbox.message.value == '') {
            alert('Error: Missing Fields.');
            return;
        }
        var message = chatbox.message.value;
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState==4&&xmlhttp.status==100) {
                document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
            }
        }

        xmlhttp.open('GET','chat.php?message='+message, true);
        xmlhttp.send();
        chatbox.reset();
    }

    $(document).ready(function(e) {
        $.ajax('logs.php', {
            ifModified: true,
            complete: function(jqxhrResponse) {
                $('#chatlog').html(jqxhrResponse.responseText);
                // scroll to the bottom here
                scrollToNewMessage();
            }
        })
    });

    var allowScroll = true;
    $('#chatlog').scroll(function() {
        allowScroll = isNearBottom();
    });

    function isNearBottom() {
        var leeway = 10;
        $(window).scroll(function() {
            return $(window).scrollTop() + $(window).height() > $(document).height() - leeway;
    });
}

function scrollToNewMessage() {
  if (allowScroll) {
    $("#chatlog").animate({ scrollTop: $('#chatlog').prop("scrollHeight")}, 1000);
  }
}
</script>

chat.php:

<?php
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();

    if  (isset($_SESSION['id'])) {
        $userId = $_SESSION['id'];
        $username = $_SESSION['username'];
        $userLabel = $_SESSION['nickname'];
    }

    $connect = mysqli_connect("", "", "", "");
    mysqli_select_db($connect, "root");
    $message = $_REQUEST['message'];
    $date = date('m/d/y');
    $time = date('H:i:s');

    mysqli_query($connect, 
                "INSERT INTO chat (name, message, time, date) 
                 VALUES ('$userLabel', '$message', '$time', '$date')"
                 );

    $result1 = mysqli_query($connect, "SELECT * FROM chat ORDER by id");
    while ($extract = mysqli_fetch_assoc($result1)) {
        echo $extract['name'] . ": " . $extract['message'];
    }
?>

logs.php:

<?php
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();

    if  (isset($_SESSION['id'])) {
        $userId = $_SESSION['id'];
        $username = $_SESSION['username'];
        $userLabel = $_SESSION['nickname'];
    }

    $connect = mysqli_connect("", "", "", "root");
    mysqli_select_db($connect, "root");
    $day = date('m/d/y');
    $result1 = mysqli_query($connect, "SELECT * 
                                       FROM (SELECT * 
                                             FROM chat 
                                             WHERE date = '$day' 
                                             ORDER BY id DESC 
                                             LIMIT 100) x                                      
                                       ORDER BY id ASC
                                       ");

    while ($extract = mysqli_fetch_assoc($result1)) {
            echo "
            <div class='usermessage'>
                <div class='mheader'>
                    <h1 style='color:".$color."'>" . $extract['time'] . "</h1>
                    <h2 style='color:".$color."'>" . $extract['date'] . "</h2>
                    <h3 style='color:".$color."'>" . $extract['name'] . "</h3>
                </div>
                <p>" . $extract['message'] . "</p>
            </div>";
        }
?>

1 个答案:

答案 0 :(得分:0)

我要做的是在PHP端将消息放入JSON格式并为每条消息添加一个id,当您拉入消息时,将last_message_id变量设置为最后一个id。这样,您只能请求自上次ID以来新的消息。

此外,如果用户在那里,您只应滚动到消息的底部,您可以设置变量以继续滚动新消息,但是当用户向上滚动时,将其设置为false,这样它就会赢得“消息”。继续向下滚动。