2014-11-24 121 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);