A more user-friendly way to implement Ajax (real-time display of background processing progress.) ) _ajax Related

Source: Internet
Author: User
Tags flush
Ajax applications are more and more, most of the Ajax processing is in the foreground display 1 "Loading ...", and then submit the data to the server for processing, after processing, show "processing completed." Can we make Ajax more user-friendly and show the progress of server processing in real time? This is especially important in some long requests, such as uploading files, sending mail, and processing data in batches. The answer, of course, is yes, or it's not going to be written, right, ^_^.

the problems that exist:
To address the functionality above, there are several issues to address:

1. How the server transmits part response to the browser after processing a portion of the data.
2, how the browser can handle the server to pass some of the data, and maintain the HTTP connection until processing completely completed.

To solve the 1th problem, the use of flush so that response block for rendering can be, specific please refer to me another essay "Flush Let the page block, step-by-step presentation";
2nd, you need to use the XMLHttpRequest readyState state, and the readyState defines the following values for the consortium:
Unsent = 0; No request sent
Opened = 1; HTTP connection already turned on
headers_received = 2; Received the response header
LOADING = 3; Really receive response body
Done = 4; Request received complete
Believe that the state 4 everyone is used every day, and we need to use here is the state 3.
Instance:
Needless to say, code instances are more useful than any literal explanation. We assume that the server's 1 processing needs 6 seconds, processing 1 records per second, a total of 6 records, we need the server every processing 1 data, the client will display the processing progress (including text and progress bar).
Server-side code (JSP code below):
Copy Code code as follows:

<%
The following settings are content-type:application/x-javascript to accommodate the WebKit browser (Chrome,safari)
Response.setheader ("Content-type", "Application/x-javascript");
int count = 6; Processing 6 data
for (int i=0;i<count;i++) {
Finished processing one, output the result to the client
Out.println (i+1);
Out.flush ();
This assumes that each data processing time is 1 seconds
Thread.CurrentThread (). Sleep (1000);
}
%>

HTML code:
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<style>
#divProgress {width:300px;height:24px;position:relative;}
#divProgress div{position:absolute;left:0;top:0;height:24px;}
#progressBg {background-color: #B9F8F9; z-index:10;}
#progressText {z-index:15;text-align:center;width:100%;}
</style>
<body>
<div id= "Divprogress" >
<div id= "PROGRESSBG" ></div>
<div id= "Progresstext" ></div>
</div>
<br/>
<button onclick= "Send ()" > Submit data </button>
<script>
var t = document.getElementById ("Progresstext");
var bg = document.getElementById ("PROGRESSBG");
function Send () {
t.innerhtml = "Loading ...";
Bg.style.width = "0px";
var xhr = new window. XMLHttpRequest ();
if (!window. XMLHttpRequest) {
try {
xhr = new window. ActiveXObject ("Microsoft.XMLHTTP");
catch (e) {}
}
Xhr.open ("Post", "http://localhost:801/ChunkTest/chunk.jsp?count=6");
var oldsize=0;
Xhr.onreadystatechange = function () {
if (Xhr.readystate > 2) {
var tmptext = xhr.responseText.substring (oldsize);
Oldsize = Xhr.responseText.length;
if (Tmptext.length > 0) {
Set text
t.innerhtml = Tmptext + "/6";
Set progress bar
var width = parseint (tmptext)/6*300;
Bg.style.width = width+ "px";
}
}
if (xhr.readystate = = 4) {
Request execution Complete
t.innerhtml = "Execution Completed";
Bg.style.width = "300px";
}
}
Xhr.send (NULL);
}
</script>
</body>

Run Effect chart:



Disadvantages:

See here maybe you're ready to try it yourself. But note that the above method is good, but also has a disadvantage, is the browser support problem. Currently, ie all versions of browsers do not support xhr.readystate = = 3 status, IE browser does not support the response response before the completion of the read ResponseText properties. Msdn:xmlhttprequest Object can be viewed specifically

Based on WebKit browser support is not very good, need to set Content-type:application/x-javascript only (after testing found content-type:text/html in some cases normal, some cases are not normal, And with Application/x-javascript are normal).

See the shortcomings have hit your enthusiasm, in fact, for IE, we do not need to do too much processing, IE does not support, will not show progress, and become the same as the traditional Ajax request, has been shown 1 loading until the request is completed. We only need to add 1 simple judgment, judge if is IE does not execute xhr.readystate > 2 code, if does not add the judgment, IE will report the JS error.

DEMO:

Demo server is not very good, and in foreign countries, may not click at any time, and sometimes the effect is not very good, you know, it is best to copy the code to the local test.
Please use Firefox or Chrome to view the effect of demo,ie viewing is nothing like the usual Ajax.
Http://213.186.44.204:8080/ChunkTest/index.html
Reprint please indicate the source: http://www.cnblogs.com/BearsTaR/. No commercial!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.