我正在尝试实现一个小型聊天应用程序,用户可以在其中与任何一个在线用户进行文本聊天。
我背后的逻辑是这样的:

 Login first.

 Fetch the users who are online from DB and show them as list of online users.

 Click on the users, then another small window is opening for text chatting.

 Create a form(two hidden fields- one is for sender id and another is for receiver id, one textarea and a button for submitting) for this chatting.

 Through jQuery, fill the value of receiver id.

 By session id, fill the value of sender id.

 After submitting the button, I call a page through ajax jquery which is responsible to insert and show the current data from DB.


我的ajaxJquery代码如下:
 

$(document).ready(function(){
        $('#send_btn').click(function(){
            var receiver_id = $('#hide_receiver_id').val();
            var sender_id = $('#hide_sender_id').val();
            var messagebox = $('#messagebox').val();

            $.ajax({
                type:"POST",
                url:"chat_history.php?receiver_id="+receiver_id+"&sender_id="+sender_id+"&message="+messagebox,
                success:function(result){
                    $('#history').html(result);
                }

            });
            $('#messagebox').val('');
        });
    });
</script>


到此为止,它的工作正常。但是我需要自动加载<div id="history"></div>部分。为此,我也在考虑通过在jQuery中使用setInterval()来实现。我的代码是这样的:

<script type="text/javascript">
  var auto_refresh = setInterval(
   function (){
    $('#history').load("chat_history.php?receiver_id=''&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
   }, 1000); // refresh every 1000 milliseconds
</script>


但是在这种情况下,如何在receiever_id中传递load()的值,这对于从DB中查找相应数据是必需的?
请让我知道是否已清除您的要求。

提前致谢。

最佳答案

<script>
    $(function () {

        // function wide variables
        var receiver_id = $('#hide_receiver_id').val();
        var sender_id = $('#hide_sender_id').val();
        var messagebox = $('#messagebox').val();

        // button click
        $('#send_btn').click(function () {
            receiver_id = $('#hide_receiver_id').val();
            sender_id = $('#hide_sender_id').val();
            messagebox = $('#messagebox').val();

            $.ajax({
                type : "POST",
                url : "chat_history.php?receiver_id=" + receiver_id + "&sender_id=" + sender_id + "&message=" + messagebox,
                success : function (result) {
                    $('#history').html(result);
                }
            });
            $('#messagebox').val('');
        });

        var auto_refresh = setInterval(function(){
            $('#history').load("chat_history.php?receiver_id="+receiver_id+"&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
        }, 1000); // refresh every 1000 milliseconds
    });
</script>

关于php - 在php,mysql和ajax jquery中开发Chat模块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17046251/

10-10 23:37