php - Laravel 聊天中的长轮询 : Why is the div not updating itself?

标签 php mysql ajax laravel-4 long-polling

我正在尝试构建一个具有长轮询功能的 Laravel 聊天应用程序(我知道有 nodejs/redis 但有一个 problem ),因此我一直在尝试实现这个 example进入 Laravel 和 MySQL。

但是,AJAX GET 状态请求始终卡在待处理...。我认为这可能是它不更新的原因 div,我在同一页面上显示来自 AJAX POST 请求的新输入的值。目前,div 仅在刷新时更新自身。

这是我的代码:

查看

function getMsg(timestamp){
    var queryString = {"timestamp":timestamp};
    $.get(
        "create",
        queryString,
        function(data){
            var obj = $.parseJSON(data);
            console.log(obj.timestamp);
            $('#response').append('<p>'+obj.body+'</p>');
            getMsg(obj.timestamp);
        }
    ).fail( function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
        });
}
getMsg();

Controller

public function create()
{
    $Msg = new Chatting;
    if(Request::ajax()){
        set_time_limit(0);
        session_write_close();
        while(true){

            $last_ajax_call = isset($_GET['timestamp'])?(int)$_GET['timestamp']:null;

            clearstatcache();
            $last_timestamp = $Msg->select(array('created_at'))->orderBy('created_at','desc')->first();
            $last_change = json_decode($last_timestamp);
            if($last_ajax_call == null || $last_change->created_at > $last_ajax_call){
                $result = array(
                    'body'=> $Msg->select('body','created_at')->where('created_at','=',$last_change->created_at)->first()->body,
                    'timestamp'=> $last_change->created_at
                );
                $json = json_encode($result);
                echo $json;
                break;
            }else{
                sleep(1);
            }
        }

    }else{
        $msgdata = $Msg->select(array('created_at','body'))->orderBy('created_at','asc')->get();
        return View::make('brightcms.Chatting.Chatting',compact('msgdata'));
    }
}

GET 请求 header

Request URL:http://localhost/msgsys/public/cms/Chatting/create?timestamp=2014-06-09+06%3A49%3A11
Request Headers CAUTION: Provisional headers are shown.
Accept:*/*
Cache-Control:no-cache
Pragma:no-cache
Referer:http://localhost/msgsys/public/cms/Chatting/create
Chrome/35.0.1916.114 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
timestamp:2014-06-09 06:49:11

顺便说一句,最佳方法的奖励积分:

  1. 改进代码,以便充分利用 Laravel 4 的功能和工作方式。
  2. 在dreamhost/共享服务器上运行NodeJS,没有任何限制。目前,有这个problem .

那么,是的,如何修复我的代码,以便当我输入新值时,应用程序将更新 div 以像实时应用程序一样显示新输入的值?

我对 Laravel 还很陌生,希望得到批评/建议。非常感谢!

最佳答案

据我所知,我认为无限 while 循环是这里的问题。

PHP 和套接字

如果您无法使用 NodeJS,请尝试使用 Sockets 的 PHP。应该可以很好地做到这一点!

改进

您说过您正在寻求改进。他们在这里。
另外,我会使用 Angular 将从服务器检索的数据绑定(bind)到 View 。

View 文件

<html>
    <head>
        <title></title>
        {{ HTML::script('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js') }}
        <style>
            #chat {
                width: 300px;
            }
            #input {
                border: 1px solid #ccc;
                width: 100%;
                height: 30px;
            }
            #messages {
                padding-top: 5px;
            }
            #messages > div {
                background: #eee;
                padding: 10px;
                margin-bottom: 5px;
                border-radius: 4px;
            }
        </style>
    </head>
    <body>
        <div id="chat">
            <input id="input" type="text" name="message" value="">
            <div id="messages">
            </div>
        </div>

        <script>
            var $messagesWrapper = $('#messages');

            // Append message to the wrapper,
            // which holds the conversation.
            var appendMessage = function(data) {
                var message = document.createElement('div');
                message.innerHTML = data.body;
                message.dataset.created_at = data.created_at;
                $messagesWrapper.append(message);
            };

            // Load messages from the server.
            // After request is completed, queue
            // another call
            var updateMessages = function() {
                var lastMessage = $messagesWrapper.find('> div:last-child')[0];
                $.ajax({
                    type: "POST",
                    url: '{{ url('chat/refresh') }}',
                    data: {
                        from: ! lastMessage ? '' : lastMessage.dataset.created_at
                    },
                    success: function(messages) {
                        $.each(messages, function() {
                            appendMessage(this);
                        });
                    },
                    error: function() {
                        console.log('Ooops, something happened!');
                    },
                    complete: function() {
                        window.setTimeout(updateMessages, 2000);
                    },
                    dataType: 'json'
                });
            };

            // Send message to server.
            // Server returns this message and message
            // is appended to the conversation.
            var sendMessage = function(input) {
                if (input.value.trim() === '') { return; }

                input.disabled = true;
                $.ajax({
                    type: "POST",
                    url: '{{ url('/chat') }}',
                    data: { message: input.value },
                    success: function(message) {
                        appendMessage(message);
                    },
                    error: function() {
                        alert('Ooops, something happened!');
                    },
                    complete: function() {
                        input.value = '';
                        input.disabled = false;
                    },
                    dataType: 'json'
                });
            };

            // Send message to the servet on enter
            $('#input').on('keypress', function(e) {
                // Enter is pressed
                if (e.charCode === 13) {
                    e.preventDefault();
                    sendMessage(this);
                }
            });

            // Start loop which get messages from server.
            updateMessages();
        </script>
    </body>
</html>

路线

Route::post('chat/refresh', function() {
    $from = Input::get('from', null);

    if (is_null($from)) {
        $messages = Message::take(10);
    } else {
        $messages = Message::where('created_at', '>', $from);
    }

    return $messages->latest()->get();
});

Route::post('chat', function() {
    return Message::create(['body' => Input::get('message')]);
});

Route::get('chat', function() {
    return View::make('chat');
});

型号

class Message extends Eloquent
{

    protected $fillable = ['body'];
}

我认为,代码非常简单......注释应该解释一切。

关于php - Laravel 聊天中的长轮询 : Why is the div not updating itself?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24115780/

相关文章:

javascript - 嵌套跨度没有拾取 onClick

php - 返回空字符串或空值是否有更多优势?

javascript - 使用 Ajax 加载 html 后调用 jquery 插件

javascript - 从一个子域到另一个子域的 AJAX 请求,但在同一个域上

jquery - 使用 jQuery ajax 上传图像的建议

php - 在单个文件中使用两个命名空间以实现向后兼容性的最佳实践是什么?

javascript - PHP 页面上未加载 Highcharts

mysql - 如何防止用户访问特定模式?

php - LastInsertId PHP

javascript - 表之间的序列化和查询