Thinkphp combines AJAX long polling to implement PC and APP push
This article mainly introduces Thinkphp combined with AJAX long polling to realize PC and APP push. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
Preface
This article mainly introduces to you the relevant content about Thinkphp combined with AJAX long polling to realize PC and APP push. It is shared for your reference and study. Without further ado, Let’s take a look at the detailed introduction.
Implementing logic
After a certain operation (such as creating a new announcement), trigger the simultaneous push of messages to all users or designated users of the APP or mobile WEB.
Regardless of performance, some people will still use it. The implementation is as follows (based on Thinkphp5 message push):
PHP long polling
/* * long轮询 API查询接口 */ public function id_log() { if (request()->isPost()) { $id = $this->param['id']; set_time_limit(0); $id_log = Db::name('table')->alias('c') ->join('table cc', 'c.youname=cc.youname', 'left') ->join('table a', 'cc.youname =a.youname ', 'left') ->join('table u', 'c.youname =u.youname ', 'left') ->field('') ->where('', $id) ->order('log_time desc') ->limit(1) ->select(); while (true) { if ($id_log) { $id_log_set = Db::name('table2') ->where('', $id) ->limit(1) ->setField('log_flag', '1'); $this->response($id_log); } $this->wrong(404100); usleep(2000); } }; }
Replace with your own table and related related fields.
Push message creation method
/** * 创建消息日志 触发操作方法 * @param string $log_content 日志内容 * @param string $log_type 日志类型 * @param int $log_c_id A用户ID * @param string $log_user B用户ID * @param string $log_admin PC * @param string $log_status * @return array */ function createLog($log_c_id, $log_type, $log_content, $log_admin, $log_user,$log_status) { $data = [ 'log_c_id' => $log_c_id, 'log_ip' => get_client_ip(), 'log_admin' => $log_admin, 'log_time' => date("Y-m-d H:i:s", time()), 'log_url' => get_url(), 'log_type' => $log_type, 'log_content' => $log_content, 'log_user' => $log_user, 'log_status'=>$log_status ]; $logadd = \think\Db::name('table')->insertGetId($data); return $logadd; }
Adopt data inventory message and detect and design flag Push in the form, otherwise offline messages will not be pushed. Likewise, you need to modify it into your own data structure!
AJAX long polling
##
var getting = { url: '{:url("youapi/url")}', dataType: 'json', success: function (res) { $(".count").text($('.llt').children().size()); $(".llt").remove(); if(res.length!=null){ $.each(res, function (index, item) { $(".notification").append('<li class="llt" data-ccid="' + item.id + '"><a href="{:url(" rel="external nofollow" admin/carloan/edit")}?id='+item.log_c_id+'"><span class="label label-info"><i class="icon-bullhorn"></i></span><span class="message">' + item.u_name + ':' + item.log_content + '</span><span class="time"><span class="liveTime">' + item.log_time + '</span></span></a></li>'); }); }else{ } } }; //关键在这里,Ajax定时访问服务端,不断获取数据 ,这里是1秒请求一次。 window.setInterval(function () { $.ajax(getting) }, 1000);Related recommendations:
Detailed explanation of Thinkphp combination ajaxFileUpload implements asynchronous image transmission sample code
ThinkPHP combines ajax and Mysql to implement client communication function code example_PHP tutorial
The above is the detailed content of Thinkphp combines AJAX long polling to implement PC and APP push. For more information, please follow other related articles on the PHP Chinese website!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
