2016-06-13 145 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秒彈出一個彈出窗口打個招呼但不刷新標記 –