AJAX以渐进的方式读取数据,不只是当它完成当它、方式、数据、AJAX

2023-09-10 16:16:45 作者:爱在夜里翻墙

我喜欢创造我的Ajax调用一个进度条。 为此,我可以让我的服务器端脚本来回报它的进展情况。 所以,我需要的JavaScript来阅读进步水平表现出来。

I like to create a progress bar for my ajax calls. For this I can make my server side script to return the state of it's progress. So I need for javascript to read this progress level and show it.

是否有可能还是我在错误的道路?

Is it possible or am I on the wrong road?

推荐答案

您可以尝试这样的事情(一些伪code,假设jQuery的,因为你已经标记了问题本身):

You could try something like this (some pseudocode, assuming jQuery, since you've tagged the question as such):

var poll;
$.ajax({
  url: 'your_ajax_script',
  beforeSend: function(){ // set up out-of-band status polling
    poll = setInterval( function(){
      $.get('your_script_that_returns_status',
        function(data){ 
          update_progressbar(data);
        });
      }, 1000 ); // update every second?
  },
  success: function(data) {
    clearInterval( poll ); // stop polling
    finalize_or_hide_progressbar(); // clean up
    do_something_with( data ); // your "done" logic
  }
});