AJAX read data in a progressive manner not just wh

2019-03-22 05:00发布

问题:

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?

回答1:

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
  }
});


回答2:

Either poll at intervals, returning the payload on the final successful call, or run two AJAX calls - the first retrieving the actual data, and the second polling for update percentage.