如何使用PHP和JQuery来开发像facebook一样的警报系统?
问题描述:
我该如何开发一个像Facebook这样的警报系统,其中用户A添加用户B,用户B将在头像上的好友请求部分获得一些号码,如下图所示。我该如何开发类似的东西? 我们如何获得这样的数字??我如何获得PHP和JQuery代码? 如何使用PHP和JQuery来开发像facebook一样的警报系统?
答
你想提醒用户A的手段我相信,当用户B“朋友”他/她,而无需刷新页面?
这需要“AJAX”。 AJAX代表异步Javascript和XML,但这是一个超载的术语,现在的实际交换数据结构通常使用JSON而不是XML。 JSON是JavaScript对象表示法。无论如何,这个想法是,你的网页 - 没有被刷新 - 可以定期调用你的服务器来获取新的或更新的信息来更新显示。使用PHP和jQuery,你要首先建立AJAX调用您的网页上是这样的:
$(function() { // on document ready
function updateAlerts() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
// Update the DOM to show the new alerts!
if (response.friendRequests > 0) {
// update the number in the DOM and make sure it is visible...
$('#unreadFriendRequestsNum').show().text(response.friendRequests);
}
else {
// Hide the number, since there are no pending friend requests
$('#unreadFriendRequestsNum').hide();
}
// Do something similar for unreadMessages, if required...
}
});
setTimeout('updateAlerts()', 15000); // Every 15 seconds.
}
});
这意志,每15秒,在URL对您的服务器发出请求/check.php上与网页来源相同的网域。 PHP应查询您的数据库并返回未读好友请求的数量。也许是这样的:
<?php
function isValid(session) {
// given the user's session object, ensure it is valid
// and that there's no funny business
// TO BE IMPLEMENTED
}
function sanitize(input) {
// return CLEAN input
// TO BE IMPLEMENTED
}
// Be sure to check that your user's session is valid before proceeding,
// we don't want people checking other people's friend requests!
if (!isValid(session)) { exit; }
$method = sanitize($_POST['method']);
switch ($method) {
case 'checkAlerts' :
// Check DB for number of unread friend requests and or unread messages
// TO BE IMPLEMENTED
$response = ['friendRequests' => $num_friend_requests,
'messages' => $num_unread_messages ];
return json_encode($response);
exit;
case 'someOtherMethodIfRequired' :
// ...
exit;
}
?>
我不明白你能解释一点吗? – 2010-09-19 12:56:41
那是怎么回事? =) – mkoistinen 2010-09-19 15:44:50
thks .....这真的有帮助... – 2010-09-19 22:32:04