Bun*_*gle 1 javascript ajax jquery json polling
我的项目需要使用AJAX轮询JSON响应的某个URL.我发出的第一个AJAX请求警告服务器我想要一些JSON内容,它开始构建和缓存响应,为每个后续的AJAX请求发回{{status":"pending"},直到JSON准备好.此时,响应更改为JSON,其中包含我可以解析并显示在文档中的内容,一旦URL返回除{"status":"pending"}之外的任何内容,我想要执行此操作.
我已经设置了一个轮询函数,它按预期工作,从URL反复请求JSON.但问题是,即使我直接导航到URL并且可以看到完整的JSON响应已准备好并正在提供服务,它仍会继续获得响应{"status":"pending"}.出于某种原因,我的轮询功能仍然是{"status":"pending"}.
当我刷新包含轮询代码的页面时,它通常适用于第一个请求 - 即它获得完整的JSON响应.这让我相信它是某种缓存问题,但我不确定在哪里或为何.不应该每个AJAX请求得到一个新的响应,或者这是我可以在我的$ .ajax()调用中设置的东西?
这是我现在使用的代码:
function ajax_poll() {
$.ajax({
url: JSON_URL, // JSON_URL is a string containing the URL to poll
dataType: 'json',
error: function(xhr_data) {
display_error();
},
success: function(xhr_data) {
if (xhr_data.status == 'pending') {
poll++; // increment poll counter // poll is a global variable to track the number of requests made
if (poll < POLLS) { // POLLS is a global variable to set the maximum number of requests
setTimeout(function() { ajax_poll(); }, INTERVAL); // wait INTERVAL before another AJAX request
} else {
display_error();
}
} else {
success(xhr_data);
}
},
contentType: 'application/json'
});
}
Run Code Online (Sandbox Code Playgroud)
success()是在页面上显示JSON内容(即我正在等待轮询时可用的内容)的函数.
值得注意的是,在本地测试代码时,轮询本地.json测试文件,我可以将文件的内容从{"status":"pending"}更改为包含我正在寻找的内容的响应,保存轮询实例之间的文件,并在下次轮询时,我的代码看到新内容并按预期工作.它只是在暂存环境中不起作用.