2016-06-13 109 views
1

我目前正在开发一个项目,但无法真正弄清楚如何刷新AJAX请求。 目前我的代码工作正常,我可以显示所有的标记,但我想每5秒刷新一次,并收到新的! 下面我的脚本的副本,我尝试使用setInterval没有成功喷射! 对此的帮助将非常棒。 再次感谢。AJAX获取请求,每5秒刷新一次

var gMapsLoaded = false; 
window.gMapsCallback = function(){ 
    gMapsLoaded = true; 
    $(window).trigger('gMapsLoaded'); 
} 
window.loadGoogleMaps = function(){ 
    if(gMapsLoaded) return window.gMapsCallback(); 
    var script_tag = document.createElement('script'); 
    script_tag.setAttribute("type","text/javascript"); 
    script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback"); 
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); 
} 


$(document).ready(function(){ 
    function initialize(){ 
     var mapOptions = { 
      zoom: 18, 
      center: new google.maps.LatLng(51.5207239719, -0.182568696184), 
      mapTypeId: google.maps.MapTypeId.ROADMAP}; 
     map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions); 
    } 
    $(window).bind('gMapsLoaded', initialize); 
    window.loadGoogleMaps(); 
}); 

$(window).load(function update() { 


    $.ajax({ 
     url: 'get-last.php', 
     success:function(data){ 
      //Loop through each location. 
      $.each(data, function(){ 
       //Plot the location as a marker 
       var pos = new google.maps.LatLng(this.latitude, this.longitude); 
       new google.maps.Marker({ 
        position: pos, 
        map: map 
       }); 




      }); 
     } , complete: function() { 
     setInterval(update, 1000); 
     } 

     }); 

回答

0

您是否试图将update()函数包装在setInterval()中,而不是在完成回调时执行?此外,我看不到你在哪儿定义map变量

$(window).load(function(){ 
    update() 
    setInterval(function(){ 
     update() 
    }, 5000) 
}) 

function update(){ 
    $.ajax({ 
     url: 'get-last.php', 
     success:function(data){ 
      //Loop through each location. 
      $.each(data, function(){ 
       //Plot the location as a marker 
       var pos = new google.maps.LatLng(this.latitude, this.longitude); 
       new google.maps.Marker({ 
        position: pos, 
        map: map //is this been set globally? 
       }); 
      }); 
     } 
    }) 
} 
+0

感谢您的时间,您的函数仅在我加载页面并删除标记加载5秒后才起作用。任何更新? –

+0

@riccardotrevisan对不起忘了添加页面加载功能。加载时添加'update()'。那是你想要达到的目标吗? – Chay22

+0

是的,现在工作很好。谢谢'Chay22'你拯救我的生活。真的很好的工作伙伴。 –

0

使用setTimeout(function(){ alert("Hello"); }, 3000);函数为此。 它会执行该功能,并在经过特定的时间重新计算后

+0

感谢,纳林,你的建议是好的,但提醒我只是我第一次加载页面,而不是每3秒。我做错了什么? –

+0

实际上我用setInterval替换setTimeout,每3秒弹出一个弹出窗口打个招呼但不刷新标记 –