针对JSON响应的jQuery AJAX轮询,基于AJAX结果或JSON内容的处理

我是一个新手到中级的JavaScript / jQuery程序员,所以具体/可执行的例子将非常感激。

我的项目需要使用AJAX来轮询一个URL,该URL返回包含要添加到DOM的内容的JSON,或者消息{“status”:“pending”} ,指示后端仍在使用内容生成JSON响应。 这个想法是,对URL的第一个请求触发后端开始build立一个JSON响应(然后被caching),随后的调用检查这个JSON是否准备好(在这种情况下提供)。

在我的脚本中,我需要以15秒的间隔轮询这个URL,最长1:30分钟,然后执行以下操作:

  • 如果AJAX请求导致错误,请终止脚本。
  • 如果AJAX请求成功,并且JSON内容包含{“status”:“pending”} ,请继续轮询。
  • 如果AJAX请求成功,并且JSON内容包含可用内容(即{“status”:“pending”}以外的任何有效响应),则显示该内容,停止轮询并终止脚本。

我已经尝试了一些有限的方法,但是我感觉它们比所需要的更加混乱。 下面是我成功使用的一个骨架函数,一次只能创build一个AJAX请求,如果从JSON响应中获得可用的内容,就可以完成它的工作:

// make the AJAX request function ajax_request() { $.ajax({ url: JSON_URL, // JSON_URL is a global variable dataType: 'json', error: function(xhr_data) { // terminate the script }, success: function(xhr_data) { if (xhr_data.status == 'pending') { // continue polling } else { success(xhr_data); } }, contentType: 'application/json' }); } 

但是,除非接收到包含可用内容的有效JSON响应,否则这个函数目前什么也不做。

我不知道该怎么做只是评论的行。 我怀疑另一个函数应该处理轮询,并根据需要调用ajax _ request(),但我不知道ajax _ request()的最优雅的方式将其结果返回给轮询函数,以便它可以响应适当。

很感谢任何forms的帮助! 请让我知道,如果我可以提供更多的信息。 谢谢!

您可以使用简单的超时recursion调用ajax_request。

 success: function(xhr_data) { console.log(xhr_data); if (xhr_data.status == 'pending') { setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again } else { success(xhr_data); } } 

坚持一个计数器检查这条线,你有最大数量的民意调查。

 if (xhr_data.status == 'pending') { if (cnt < 6) { cnt++; setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again } } 

除非你想提醒或什么东西,否则你不需要在你的错误function中做任何事情。 错误的简单事实将阻止成功函数被调用并可能触发另一轮询。

非常感谢你的function。 这是一个小错误,但这里是修复。 roosteronacid的答案在达到100%后不会停止,因为clearInterval函数有错误的用法。

这是一个工作function:

 $(function () { var statusElement = $("#status"); // this function will run each 1000 ms until stopped with clearInterval() var i = setInterval(function () { $.ajax( { success: function (json) { // progress from 1-100 statusElement.text(json.progress + "%"); // when the worker process is done (reached 100%), stop execution if (json.progress == 100) clearInterval(i); }, error: function () { // on error, stop execution clearInterval(i); } }); }, 1000); }); 

clearInterval()函数将间隔id作为参数,然后一切都很好;-)

干杯尼克

closures我的头顶上:

 $(function () { // reference cache to speed up the process of querying for the status element var statusElement = $("#status"); // this function will run each 1000 ms until stopped with clearInterval() var i = setInterval(function () { $.ajax( { success: function (json) { // progress from 1-100 statusElement.text(json.progress + "%"); // when the worker process is done (reached 100%), stop execution if (json.progress == 100) i.clearInterval(); }, error: function () { // on error, stop execution i.clearInterval(); } }); }, 1000); }); 

您可以使用javascript setInterval函数每5秒加载一次内容。

 var auto= $('#content'), refreshed_content; refreshed_content = setInterval(function(){ auto.fadeOut('slow').load("result.php).fadeIn("slow");}, 3000); 

供你参考-

每3秒自动刷新div内容