When using Ajax for information interaction, if the information returned by the server is relatively large, the streaming display is more friendly than the unified display after the transfer is complete.
Streaming implementation
The principle is to set the timer, periodically check the status of the Ajax object and update the content, if the transfer is complete, cancel the timer.
- function Ajax_stream (url,data,element) {
- var xmlhttp=null;
- if (window. XMLHttpRequest)
- {//code for IE7, Firefox, Opera, etc.
- Xmlhttp=new XMLHttpRequest ();
- }
- else if (window. ActiveXObject)
- {//code for IE6, IE5
- Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
- }
- if (xmlhttp==null)
- {
- Alert ("Your browser does not support XMLHTTP.");
- Element.val (' Your browser does not support XMLHTTP. Click the LOG link to monitor the procedure. ');
- return 0;
- }
- var xhr = xmlHttp;
- Xhr.open (' POST ', url, true);
- If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method:
- Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
- Xhr.send (data);
- var timer;
- Timer = Window.setinterval (function () {
- if (xhr.readystate = = Xmlhttprequest.done) {
- Window.cleartimeout (timer);
- }
- Element.val (Xhr.responsetext);
- }, 1000);
- }
Post Data conversion
Because send in the standard implementation can only accept the following types of inputs, it is better to convert the data objects that need to be passed into a string or formdata format in advance, which is not asJQuery, but how jquery can implement event response in the middle of the transmission is not known, so it cannot be used, or all objects can be converted to JSON.
- void Send ();
- void Send (ArrayBuffer data);
- void Send (Blob data);
- void Send (Document data);
- void Send (domstring data);
- void Send (FormData data);
The following is the code of the conversion, if the browser supports Formdata conversion, otherwise it will be converted into a string.
- function Ajax_generate_data (jsobj) {
- var i;
- if (window. FormData) {
- var data = new FormData ();
- For I in Jsobj {
- Data.append (I,jsobj[i]);
- }
- } else {
- var data = ';
- var datas = [];
- For I in Jsobj {
- For the values so, possible & contained in the strings does not break the format
- var value = encodeURIComponent (Jsobj[i]);
- Datas.append (i + ' = ' + value);
- }
- data = Datas.join (' & ')
- }
- Console.log (data);
- return data;
- }
JavaScript AJAX Stream Streaming display