2014-11-24 190 views
0

我做了一個通知系統。我希望可以通過Ajax調用允許顯示未讀通知數量的函數。有可能通過瀏覽網站,例如每10秒鐘自動調用一次該功能。謝謝你的幫助。 現在我有這樣的代碼:通過Ajax更新通知

function notifications() 
{ 
    $.get("//localhost/laravel/public/index.php/new_notifications", 
    function(data) 
    { 
     data_parsed = JSON.parse(data); 

     if(data_parsed.length > 0) 
     { 
      //code 
     } 
    }); 
} 
+1

確切地說,你的問題是什麼? – jbutler483 2014-11-24 15:36:11

+0

我會每10秒自動調用一次該函數。無需刷新頁面。 – Francesco 2014-11-24 15:43:14

回答

1

,如果你想打電話每隔幾秒鐘的功能,使用JavaScript的設置間隔應做到:

window.setInterval(function(){ 
    /// call your function here 
}, 5000); 

Source

此功能將循環/每5秒呼叫一次。

setInterval是一個標準的JavaScript函數,不是jQuery的一部分。你與執行功能,並以毫秒爲單位一個時期稱之爲:

下面是它看起來可能:

setInterval(function(){ 
    $.ajax({ url: "server", success: function(data){ 
     //Update your dashboard gauge 
     salesGauge.setValue(data.value); 
    }, dataType: "json"}); 
}, 10000); 

Source

+0

加上一個,因爲你也注意到了你的來源。我也喜歡setInterval的定義,因爲我實際上並不知道這一點。 :■ – 2014-11-24 15:49:43

0

假設你有一個包含該信息的DIV地方。

<div id="unreadNotification" ></div> 

在您的ajax調用中刷新div。

function notifications() 
{ 
    $.get("//localhost/laravel/public/index.php/new_notifications", 
    function(data) 
    { 
     data_parsed = JSON.parse(data); 

     if(data_parsed.length > 0) 
     { 
      //i don't know the structure of your data, but put the right thing here. 
      $("#unreadNotification").text(data_parsed.unreadNotification); 
     } 
    }); 
} 

每10秒調用一次該函數。

setInterval(notifications, 10000);