对不起,男孩,但我不明白你在哪里找到问题......这真的很简单
案例1:离线用户通知(服务器端)
当用户登录聊天服务时,您需要在“tbl_messages_users”中使用参数“read = 0”进行查询。然后你必须对数据库的输出进行风格化
/** I'm using PHP syntax because I'm not good with NodeJS **/
$query = new Query(...);
$results = $query->getResults();
if(count($results) > 0) {
foreach($results as $result) {
/** .... STYLISH THIS (Ex. in HTML) .... **/
}
}
trick怎么用?服务器为用户生成页面时(服务器端)
案例 2: 在线用户(客户端)
/** I'm using jQuery syntax **/
/**
* %HTTP_METHOD% : GET or POST ?
* %SERVER_SIDE_URL% : Where is the action?
* %DATA_TO_SERVER_SIDE_ACTION% : Example ClientID
*
* We use JSON Data Object because is really simple to parse in jQuery
**/
$.ajax({
type: "%HTTP_METHOD%",
url: "%SERVER_SIDE_URL%",
data: "%DATA_TO_SERVER_SIDE_ACTION%"
}).done(function(json) {
/** indexOf prevent invalid HTML characters **/
json = json.substring(json.indexOf("{"));
json = $.parseJSON(json);
/** Create Your JSON Data Structure, iterate It and generate HTML to append in notification panel **/
}).fail(function(httpResponse) {
/**
* Stylish an HTML exception
* httpResponse : Contains Server HTTP response data (Ex. response code like 200, ..., 500)
**/
});
如何调用 Ajax 请求?
setTimeout(function() {
myAjaxRequest( ...params ):
}, %EVERY_X_MILLISECONDS%);
或使用触发器
$(document).on("%MY_TRIGGER%", myCallbackFunction);
function myCallbackFunction(e) {
myAjaxRequest( ...params ):
}
如何使用技巧?当用户调用服务器 API(客户端)时
将案例 1 与案例 2 结合
在%SERVER_SIDE_URL%(案例2)中可以放一个返回JSON数据对象的URL
/** I'm using PHP syntax because I'm not good with NodeJS **/
$query = new Query(...);
$results = $query->getResults();
$RESULT = array();
if(count($results) > 0) {
$RESULT['status'] = 'OK';
$RESULT['unreadMessages'] = array();
foreach($results as $result) {
$RESULT['unreadMessages'][] = array(
'message' => $result->message,
'date' => $result->messageDate,
/** ... etc **/
);
}
} else {
$RESULT = array(
'status' => 'KO',
'error' => 'No unread messages for user %USER_ID%',
);
}
echo json_encode($RESULT);
exit; /** PREVENT SCRIPT TO REMAIN ALIVE IN BACKGROUND **/
之后
通过 Ajax 请求调用服务器页面(见案例 2)
结论
当用户登录聊天系统或用户也进入聊天系统时,您可以使用案例 2。只需在需要时启动 jQuery 触发器! =)