Makes ajax more user-friendly (displays the background processing progress in real time .)

Source: Internet
Author: User

There are more and more ajax applications. Most of the ajax processing is to display a "loading..." on the front-end, and then submit the data to the server for processing. After the processing is completed, the "processing completed" is displayed ". Can we make ajax more friendly and display the progress of server processing in real time? This is particularly important in some long-time requests, such as uploading files, sending emails, and batch processing data. Of course the answer is yes, otherwise it won't be written, right, ^ _ ^.

Problems:
To implement the above functions, you need to solve the following problems:

1. How does the server transmit partial response to the browser after processing part of the data.
2. How can the browser process part of the data transmitted by the server and maintain the http connection until the processing is complete.

To solve the 1st problems, you can use flush to render response parts. For details, refer to "flush to split pages and present them gradually ";
2nd problems, the readyState state of XMLHttpRequest is required. w3c defines the following values for readyState:
UNSENT = 0; // No request is sent
OPENED = 1; // The http connection has been enabled.
HEADERS_RECEIVED = 2; // receives the response header.
LOADING = 3; // truly receives the response body
DONE = 4; // The request has been received
I believe that status 4 is used every day, and we need to use status 3 here.
Instance:
To put it bluntly, code instances are more useful than any text explanation. Let's assume that it takes 6 seconds for the server to process one record, and 6 records are processed in total. We need the server to process one record at a time, the client displays the processing progress (including text and progress bars ).
Server code (the following JSP code ):
Copy codeThe Code is as follows:
<%
// Set Content-Type below: application/x-javascript to adapt to Webkit browsers (chrome, safari)
Response. setHeader ("Content-Type", "application/x-javascript ");
Int count = 6; // process 6 data records
For (int I = 0; I <count; I ++ ){
// After processing, output the result to the client.
Out. println (I + 1 );
Out. flush ();
// Assume that each data processing time is 1 second.
Thread. currentThread (). sleep (1000 );
}
%>

Html code:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<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>
</Head>
<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 the progress bar
Var width = parseInt (tmpText)/6*300;
Bg. style. width = width + "px ";
}
}
If (xhr. readyState = 4 ){
// The request has been executed.
T. innerHTML = "completed ";
Bg. style. width = "300px ";
}
}
Xhr. send (null );
}
</Script>
</Body>
</Html>

Run:



Disadvantages:

You may be ready to try it on your own. But note that the above method is good, but it also has a disadvantage, that is, the browser support problem. Currently, browsers of all IE versions do not support xhr. readyState = 3. IE does not support reading the responseText Attribute before the response is complete. For details, refer to MSDN: XMLHttpRequest Object.

The Webkit-based browser does not support very well. You need to set Content-Type: application/x-javascript (the test shows that Content-Type: text/html works normally in some situations, in some cases, application/x-javascript is normal ).

After seeing the disadvantages, does it hurt your enthusiasm? In fact, for IE, we don't need to deal with it too much. If IE doesn't support it, it won't show the progress, just like a traditional ajax request, one loading is displayed until the request is complete. We only need to add one simple judgment. If the judgment is ie, no code in xhr. readyState> 2 will be executed. If the judgment is not executed, a JS error will be reported in IE.

DEMO:

The demo server is not very good, and may not be able to be clicked at any time outside of China, and sometimes the running effect is not very good. As you know, it is best to copy the code to the local for testing.
Please use firefox or chrome to view the demo. The effect of ie is no different from that of normal ajax.
Http: // 213.186.44.204: 8080/ChunkTest/index.html
For more information, see http://www.cnblogs.com/bearstar /. Commercial use prohibited!

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.