我们偶尔可能会遇到这样一个问题,即当页面后的数据更新时,页面却没有反映这种更新.因为,为了节省时间,浏览器会在本地缓存页面,然后从缓存中找出该页面而不是重载该页面.这一问题在IE中非常常见,因为除非用户强制不缓存页面,否则IE会自动缓存页面.
该问题的通常解决办法是, 在页面中插入以下代码:
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
这足以强制浏览器重载该页面.但如果使用 XMLHttpRequest 对象,且请求中包含 GET 指令,那么IE 将始终缓存该页面,而绝不会重载该页面.
这个问题有 3 种解决办法.
第一种, 在 GET 请求后添加 querystring, 并确保添加的内容在每次运行时都不一样. 如下:
xHRObject.open("GET", "display.php?id=" + Number(new Date) + "&value=" + data, true);
第二种, 设置 HTTP 头部的 If-Modified-Since 为引用过去的一个日期:
xHRObject.open("GET", "display.php?value=" + data, true);
xHRobject.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
第三种, 使用 POST 请求.
var bodyofrequest = "value=";
bodyofrequest += encodeURIComponent(data); //data is the actual arguments that you want to send
xHRObject.open("POST","display.php",true);
xHRObject.setRequestHeader("Content-Type","application/x-www-from-urlencoded");
//getData is the Callback function which is binded to readystatechange event
xHRObject.onreadystatechange = getData;
xHRObject.send(bodyofrequest)