ajax处理IE不更新的cache问题
May
27
ajax处理IE不更新的cache问题
今天在弄那个wp-wisdom插件,想做成每几秒中自动刷新的问题,发现处理的时候有两种办法:
一、使用wp-cron来处理,定时调用,这里有个问题,设置这个wp-cron还是比较复杂的,况且不是人人都想随意安装插件,毕竟插件越多,速度肯定会受到影响;
二、采用ajax定时刷新不失为一个好办法,可是发现个很奇怪的问题,在Firefox或者Sofari下都能自动刷新,可是在IE下就死活没用,真郁闷呢。后来发动google的力量,终于找到了原因和解决的办法:
原来firefox 每次 request 都会重新再回一次 server 取得最新的资料,但是 IE 就不一样了,他会 cache 住之前的联机所传回的数据,只有第一次 request 时会真正的去 server 读取数据,导致画面上的数据不会随时间而更新….
解决方式就是在 ajax 所要读取的网页上加上下面 2 行控制 cache 的 header,在此以用 ajax 联机回 server 抓某一个 php 网页为例:
- header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
- header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
这样 IE 就会在每一次 request 时,重新再连回 server 了。
另一种方式是在 request 对象上设定 setRequestHeader(),如下所示:
- <script type="text/javascript" language="javascript">
- var http_request = false;
- function xmlRequest(url) {
- // branch for native XMLHttpRequest object
- if (window.XMLHttpRequest) {
- req = new XMLHttpRequest();
- req.onreadystatechange = alertContents;
- req.open("GET", url, true);
- req.setRequestHeader("If-Modified-Since","0");
- req.send(null);
- } // branch for IE/Windows ActiveX version
- else if (window.ActiveXObject) {
- req = new ActiveXObject("Microsoft.XMLHTTP");
- if (req) {
- req.onreadystatechange = alertContents;
- req.open("GET", url, true);
- //let IE refresh page
- req.setRequestHeader("If-Modified-Since","0");
- req.send();
- }
- }
- }
- function alertContents() {
- if (req.readyState == 4) {
- if (req.status == 200) {
- alert(req.responseText);
- } else {
- alert('There was a problem with the request.');
- }
- }
- }
- </script>
参考资料:做了两个月ajax,总结一些小经验
o(∩_∩)o…,感觉怎么样?这两天抽空把这个插件封装一下 ^__^


















No Comments »
No comments yet.
RSS feed for comments on this post. TrackBack URI
Leave a comment
If you want to leave a feedback to this post or to some other user´s comment, simply fill out the form below.