Setting up AJAX progress bar
Ok im new to AJAX. Kind of know about the lifecycle of a request, IE uses ActiveXObject stuff like that.
However now im faced with a real world problem. I have a servlet running in the background that performs a nu开发者_运维问答mber of tasks and i would like to display a progress bar to show where the process is up to and to also show that something is actually happening.
So far in the server side i can calculate the number of processes that will take place before they begin, and easily enough add a counter to increment after each process completes - therefore enabling me to find the percentage i wish to show.
In terms of where i should output the data gathered from incrementing etc i'm not sure so far it is dormant as 2 integers in the processing java class.
Any help would be much appreciated.
So far i've taken a look at this and i guess thats kind of what im aiming for.
Cheers.
Basically, you'd like to store a reference to the task and inherently also its progress in the HTTP session (or in the Servlet context if it concerns an application wide task). This way you must be able to retrieve information about it on every HTTP request.
In JavaScript, you can use setTimeout()
or setInterval()
to execute a function after a certain timeout or at certain intervals. You can use this to repeatedly fire Ajax requests to request current status of the progress. Once the status is retrieved, e.g. in flavor of an integer with a max value of 100 (the percentage), just update some div representing a progressbar and/or the percentage text accordingly in the HTML DOM tree.
jQuery is very helpful in firing ajaxical requests and traversing/manipulating the HTML DOM tree like that. It minimizes the code verbosity and crossbrowser compatibility headaches.
Imagine that the doGet()
of the servlet look like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String processId = "longProcess_" + request.getParameter("processId");
LongProcess longProcess = (LongProcess) request.getSession().getAttribute(processId);
int progress = longProcess.getProgress();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(String.valueOf(progress));
}
Then you can use it like follows:
function checkProgress() {
$.getJSON('progressServlet?processId=someid', function(progress) {
$('#progress').text(progress + "%");
$('#progress .bar').width(progress);
if (parseInt(progress) < 100) {
setTimeout(checkProgress, 1000); // Checks again after one second.
}
});
}
精彩评论