我有一个名为data.php
的PHP文件,我想使用jQuery
来调用该文件并将其内容返回到
<div id="datacontainer"></div>
每60秒一次。我在这里找到了很多关于触发事件的示例,但是我很难找到定时事件的解决方案。
使用path/to/file/data.php
将名为jQuery/Ajax
的文件的输出插入div的最佳做法是什么?
答案 0 :(得分:1)
检查一下:http://api.jquery.com/load/和https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
示例:
setInterval(function() {
$( "#datacontainer" ).load( "data.php" );
}, 60000);
还要考虑使用successCallback
和jQuery load
的{{1}},因为通常您要等到服务器返回内容。在我看来,最佳做法是:
setTimeout
但这取决于用例。
答案 1 :(得分:1)
/* set interval to call function every 60 seconds */
setInterval(function(){
/* start ajax */
$.ajax({
url: "path/to/file/data.php",
type: "GET"
}).done(function(html) {
/* when it's done, take the return and replace whatever is in the DIV with it
if you dont want to replace, but append, just use the .append(html) function */
$( '#datacontainer' ).html( html );
});
}
/*60 seconds * 1000 miliseconds*/
,60000);
答案 2 :(得分:0)
var $contentdiv = jQuery('#datacontainer');
window.setInterval(function () {
$contentdiv.load("path/to/file/data.php");
}, 60000);
如果您使用Google搜索“计时器事件javascript”,您会发现此MDN page...