使用Codeigniter和mysql进行Ajax长轮询

时间:2015-01-24 14:07:55

标签: php ajax codeigniter comet

我正在尝试使用带有codeigniter框架的ajax长轮询来实现一个简单的聊天应用程序。以下是ajax请求

var timestamp = null;
function check_incoming_chat_message(me, timestamp) {
$.ajax({
    type: "Get",
    dataType: 'json',
    url: 'http://localhost/ci/index.php/chat/check_chatbox?to_me='+me+'&timestamp='+timestamp, 
    async: true,
    //data: {to_me: me, timestamp: timestamp},
    cache: false,
    success: function(response) {
        setTimeout(check_incoming_chat_message(response.to_chat, response.timestamp),10000);
    },
    error: function(response) {
        setInterval(check_incoming_chat_message(response.to_chat, response.timestamp),2000);
    },
    complete: function() {
    }
});

}

以下是控制器端的代码,其中控件保持循环检查db,除非mysql中有新的聊天消息,在这种情况下它会将聊天消息抛出到视图。一旦我在视图中收到聊天消息,我再次触发ajax请求。(至少这是我的想法)

function check_chatbox() {
        $logged_in_user = $_GET["to_me"];
        $last = $_GET["timestamp"];
        header('Content-type: text/plain'); 
        header('Content-type: application/json'); 
        if($last == "" || $last == null) { // check if timestamp is null
            $result = $this->chat_model->current_tstamp($logged_in_user);
            foreach($result as $row)
            {
                $data = array('msg_time' => $row->msg_time,
                              'chat_message' => '',
                              'to_chat' => $logged_in_user
                );
            }
            echo json_encode($data);
            return;
        }
        $result = $this->chat_model->current_tstamp($logged_in_user);
        foreach($result as $row)
        {
            $data_array = array('msg_time' => $row->msg_time);
        }
        $current = $data_array['msg_time'];


        while($current <= $last) {
            usleep(100000);
            //clearstatcache();
            $result = $this->chat_model->current_tstamp($logged_in_user);
            foreach($result as $row)
            {
                $data = array('msg_time' => $row->msg_time);
            }
            $current = $data['msg_time'];
        }
        $result = $this->chat_model->check_new_messages($logged_in_user, $current);
        if($result) {
            foreach($result as $row)
            {
                $data = array('chat_message' => $row->chat_message,
                         'from_chat' => $row->from_chat,
                         'chat_id'   => $row->chat_id,
                         'msg_time'  => $row->msg_time
                );
            }

            echo json_encode($data);
            return;
        }
        else {
            return;
        }
    }

问题是,它会阻止页面中的所有其他请求,包括超链接(如codeigniter中的锚标签)。有人可以帮我指出我做错了什么吗?

由于

注意:我正在尝试复制此示例中使用的相同过程 http://www.mediafire.com/download/3xd0zx5ej3pp42b/comet.zip

0 个答案:

没有答案