我有一个应该是非常简单的小过程。我有一个间隔计时器,当它到期时,它会向服务器发出 ajax 调用。使用返回的 json,解析它并更新 DOM。 setInterval 设置为一秒。然后服务器对数据库执行一个非常简单的 SELECT。如果是的话,它会执行一个需要几毫秒才能执行的查询。
在我们的测试服务器上,它运行良好。但是当它部署到我们的客户时,大多数时候它实际上并没有访问数据库。我们可以在查询分析器中看到它。应该有连续的查询流,但它们充其量是零星的,通常两次点击之间有 40 秒或更长的时间。
代码如下:
setTimeout(function run() {
// When the timer elapses, get the data from the server
GetData(0);
setTimeout(run, _refreshRate);
}, 1000);
function GetData(isFirstLoad) {
//console.log("Attempting to obtain the data...");
jQuery.ajax({
url: "something.ashx",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
//console.log("Got the data.");
ParseJson(resultData);
// show the last refresh date and time
$('#refreshTime').html(GetDateTime());
},
error : function(xhr, textStatus, errorThrown) {
if (textStatus == 'timeout') {
//console.log("Timeout occured while getting data from the server. Trying again.");
// If a timeout happens, DON'T STOP. Just keep going forever.
$.ajax(this);
return;
}
},
timeout: 0,
});
}
ParseJson(resultData);
内的所有内容工作正常。有了这条线...
$('#refreshTime').html(GetDateTime());
...即使数据库从未受到攻击,时间也会像发条一样每一秒刷新一次。
我可以在 error
内的调试工具中放置一个断点而且它永远不会被击中。
如果我们点击刷新,它会工作或几秒钟(我们可以看到查询命中数据库),但随后它会再次减慢。
令人沮丧的是它在我们的测试服务器上完美运行。但显然有一些东西我忽略了。
编辑:
好吧,这真的很奇怪。当我打开调试器时,它可以工作。一旦我关闭调试器,它就会停止工作。我什至不需要运行网络选项卡并捕获事件。只需打开调试器窗口即可使其工作。
这是 IE,这是客户正在使用的,所以它是我们唯一的选择。
最佳答案
在这里找到答案:
jQuery ajax only works in IE when the IE debugger is open
事实证明,只有 IE 才会缓存 ajax 响应。你必须告诉它不要这样做。添加 cache: false
就成功了。
function GetData(isFirstLoad) {
//console.log("Attempting to obtain the data...");
jQuery.ajax({
url: "something.ashx",
type: "GET",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(resultData) {
关于javascript - Ajax 调用 setInterval 计时器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735890/