请尝试setTimeout函数和.load函数的组合

Try the combination of setTimeout function and .load function

本文关键字:函数 load 组合 setTimeout      更新时间:2023-09-26

我对以下代码有问题。我想在文件(test.txt)发生更改时显示它的索引。虽然它使用Mozilla工作,但在IE9中,settimeout()似乎不起作用。

<div id="auto">xxx</div> 
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
  $(document).ready( function () {
    $('#auto').load('test.txt');
    refresh1();
  });
  function refresh1() {
    setTimeout ( function() {
      $('#auto').load('test.txt');
      refresh1();
    },200);     
  }
</script>

我使用了"元",以防止IE兑现,但仍然没有成功。我使用

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" /> 

如果我把IE放在一边,在上面代码工作的地方使用Mozilla,我的问题就可以解决了,但问题是我找不到使用Mozilla读/写文件的方法(非常感谢这个例子)。Mozilla/Chrome有ActiveX等价物吗?我用OSFile尝试了一些代码,但没有成功。不过,我希望避免更改浏览器。如果我们能找到一个使用IE在没有页面刷新的情况下读取"更改"文件上下文的解决方案,我会非常高兴:)

在再次调用refresh之前,您应该使用complete回调来等待响应。还要考虑刷新速度慢一点,比如2秒。

$(document).ready( function () {
  refresh1();
});
function refresh1(responseText, textStatus, XMLHttpRequest) {
  // will be used as the complete callback
  setTimeout ( function() {
    $('#auto').load('test.txt', refresh1);
  }, 200);     
}

编辑:IE也可能有意缓存您的请求,可以使用Pragma: no-cache标头进行响应,也可以在document.ready之前使用jQuery.ajaxSetup({ cache: false });,或者如评论中所述,使用.load('test.txt?' + new Date().getTime(), refresh1)

参考:

  • http://api.jquery.com/load/
  • http://api.jquery.com/jQuery.ajaxSetup/
  • http://api.jquery.com/jQuery.ajax/
  • http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
$(document).ready( function () {
    reload_interval = setInterval(function() {
       $('#auto').load('test.txt');
    }, 200) 
}

即使在IE中也应该有效。

一个完整的jquery解决方案

$('myElement').delay(200).queue(function( nxt ) {
    $(this).load('test.txt');
    nxt();
});

jQuery文档链接-延迟,队列

干杯!!