我遇到的一个问题是httRequest似乎被缓存了...... evey返回显示相同的“时间戳”......
<script type="text/javascript">
var closeMe = 0;
var logMe = 0;
//the window doesn't have focus, do nothing or something that let's them know we're not logging at the moment
function onBlur() {
///stop the log interval
clearInterval ( logMe );
//after 2 min of non focus, close it.
closeMe = setInterval('window.close()',120000); //after 2 min of non focus, close it.
}
//the window has focus... keep logging.
function onFocus(){
//stop the close counter - in the event to 'blurred' sometime
clearInterval ( closeMe );
//run the AJAX on a schedule - we're doing it every minute - bu tyou can do it as often as you like
logMe = setInterval('logTime()',60000);
}
//call a script that logs another minute...
function logTime() {
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "ajax-on-time-interval.cfm", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
}
// check for Internet Explorer... IE uses 'onfocusin/out" - everything else uses "onfocus/blur"
if (/*@cc_on!@*/false) {
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
</script>
“ajax-on-time-interval.cfm”的代码 #now()#
答案 0 :(得分:1)
IE确实缓存了Ajax请求。为了阻止我通常只是在我的请求中添加一个随机变量:
function logTime() {
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "ajax-on-time-interval.cfm?random="+Math.random(), false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
}
只要你没有在后端解析新的'random'变量,这应该可以工作: - )
答案 1 :(得分:1)
如果您只是在ping服务器并且不关心返回的内容,那么您可以使用HEAD请求而不是完全获取。
同样使用同步请求是一个非常糟糕的想法。这意味着如果与服务器的连接因任何原因而变坏,则用户的浏览器将冻结,他们将无法执行任何操作。通过在服务器端代码上添加较长的休眠时间并使用该页面来测试它。您的用户不会喜欢这种类型的ping,因此将其交换为异步。
要停止缓存,您应该首先在服务器端代码上设置正确的标头。如果未正确设置,浏览器将缓存页面。这就是获取请求的目的,以提高您的浏览效率。
如果你想强制它总是抓住最新,最简单的事情就是附加一个更改的查询字符串值。 Math.random()是一个常见的选择,但更好的选择是new Date().getTime()
,因为它在同一台机器上总是一个不同的值。
"ajax-on-time-interval.cfm?ts=" + (new Date().getTime())
答案 2 :(得分:-1)
我认为你可以使用
$.ajaxSetup({
cache: false
});
或类似的......