长轮询ajax没有保持实时更新

时间:2017-07-22 03:11:03

标签: php jquery codeigniter

我正在进行长时间的轮询,但它可以在我的网络中查看我的状态等待的长轮询等待新数据并更改数据库,但是当我尝试将一个项目插入到我的数据库中时,我尝试插入一个值显示保持实时长轮询我看不到实时更新..我该如何解决?

推动控制器编码器

public function pusher() {
    header('Content-Type: application/json');
    $user_id = $this->session->log['id'];
    set_time_limit(0);
    while (true) {
        $firstCall = false;
        if (isset($_GET['timestamp'])) {
            $last_ajax_call = $_GET['timestamp'];
        } else {
            $last_ajax_call = time();
            $firstCall = true;
        }

        clearstatcache();
        $notificationsCount = $this->notification->checkForNotifications($last_ajax_call, $user_id);
        $newData = (int) $notificationsCount > 0 ? true : false;
        $notifications = [];
        if ($newData) {
            $dataSet = $this->notification->getNotifications($user_id, $last_ajax_call);

            foreach($dataSet as $data) {
                $notifications[] = $data;
                $finalNotificationTime = $data['timestamp'];
            }

            $result = array('notifications' => $notifications, 'timestamp' => $finalNotificationTime);
            $json = json_encode($result);
            echo $json;

            break;

        } else {
            if ($firstCall) {
                $dataSet = $this->notification->getUnreadNotifications($user_id);

                foreach($dataSet as $data) {
                    $notifications[] = $data;
                }

                $result = array('notifications' => $notifications, 'timestamp' => $last_ajax_call);
                $json = json_encode($result);
                echo $json;
                break;
            }
            sleep(1);
            session_write_close();
            continue;
        }
    }
    exit();
}

ajax

function check_notifications(timestamp) {
        var queryString = {
            'timestamp': timestamp
        };

        $.ajax({
            type: 'GET',
            url: URL_GET_NOTIFICATION,
            data: queryString,
            success: function (data) {
                // put result data into "obj"
                for (var i in data.notifications) {
                    notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
                }
                check_notifications(data.timestamp);
            }
        });
    }
 check_notifications();

screenshot_network

0 个答案:

没有答案