2010-09-19 57 views

回答

17

你想提醒用戶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; 
    } 
?> 
+0

我不明白你能解釋一點嗎? – 2010-09-19 12:56:41

+0

那是怎麼回事? =) – mkoistinen 2010-09-19 15:44:50

+0

thks .....這真的有幫助... – 2010-09-19 22:32:04