2014-11-01 152 views
1

我使用jQUERY + AJAX每隔X秒刷新一對div。我想知道在頁面加載後立即(首次)加載這些div的方式,然後等待(例如30秒)每次刷新。 我已經看到,你命名一個函數,然後調用刷新。事實是,我無法弄清楚如何用我的代碼解決這個問題。AJAX + jQUERY:立即加載div,然後每隔X秒刷新一次

這裏是我的代碼行:

// <![CDATA[ 
    $(document).ready(function() { 
    $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh 
    setInterval(function() { 

    //DIVs that are being loaded 
    $('#item01_tobeloaded').load('items/item01.php'); 
    $('#item02_tobeloaded').load('items/item02.php'); 

}, 30000); // the "30000" here refers to the time to refresh the div. it is in milliseconds. 

    }); 
    // ]]> 

任何幫助將是非常讚賞:)

謝謝!

回答

2
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#refresh").load("refresh.php"); 
     var refreshId = setInterval(function() { 
      $("#refresh").load('refresh.php?' + 1*new Date()); 
     }, 1000); 
    }); 
</script> 

這個小腳本不斷加載並刷新div的'刷新',你可以根據你的需要調整它以將1000更改爲任何你需要的值。 1000會每秒刷新一次。

此行

$(document).ready(function() { 
$("#refresh").load("refresh.php"); 

負載侑在文件準備的內容,事後你可以用你的代碼

+0

謝謝哥哥棒!事實上,我有兩個以上的div。我是否必須再次回想每一個div?還是有什麼可以幫助減少代碼量?感謝您的快速回復! – nicozica 2014-11-01 20:16:50

+0

作爲你刷新頁面似乎是不同的每個div(當然),你將需要爲每個div做這個,但你可以寫一個簡單的函數,減少代碼。如果它對你有幫助,請將答案標記爲正確。 – baao 2014-11-01 20:24:09

+1

你可能想看看pjax(https://github.com/defunkt/jquery-pjax)或者dotimeout(http://benalman.com/projects/jquery-dotimeout-plugin/) – xeo 2014-11-01 20:45:15