This article mainly introduces JavaScript and AJAX_stream for stream display. For more information, see if the server returns a large amount of information when AJAX is used for information interaction, streaming display is more friendly than the unified display after transfer.
Stream implementation
The principle is to set a timer to regularly view the status of the AJAX object and update the content. if the transfer is completed, the timer is canceled.
The Code is as follows:
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 the send in the standard implementation can only accept the following types of input, it is not as convenient as converting the data object to be passed to the string or FormData format in advance, however, it is not clear how JQuery implements event response during transmission, so it cannot be used, or JSON is converted into all objects.
The Code is as follows:
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 conversion code. If the browser supports FormData, convert it to a string.
The Code is as follows:
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 that possible & contained in the strings do not break the format
Var value = encodeURIComponent (jsobj [I]);
Datas. append (I + '=' + value );
}
Data = datas. join ('&')
}
Console. log (data );
Return data;
}