長(zhǎng)輪詢(xún)
- 和服務(wù)器始終保持一個(gè)連接场躯。
- 如果當(dāng)前連接請(qǐng)求成功后,將更新數(shù)據(jù)并且繼續(xù)創(chuàng)建一個(gè)新的連接和服務(wù)器保持聯(lián)系。
- 如果連接超時(shí)或發(fā)生異常猖辫,這個(gè)時(shí)候程序也會(huì)創(chuàng)建一個(gè)新連接繼續(xù)請(qǐng)求。
這樣就大大節(jié)省了服務(wù)器和網(wǎng)絡(luò)資源砚殿,提高了程序的性能啃憎,從而也保證了程序的順序。
jquery 寫(xiě)法
$(function(){
// 這里模擬form表單方式請(qǐng)求數(shù)據(jù)似炎,因?yàn)樾枰枰缬? var form = $.StandardPost('http://xxx.14.6.xxx:8888/',{
product_code: 'CLZ7',
type: '1'
});
var options = {
target: '#output', //把服務(wù)器返回的內(nèi)容放入id為output的元素中
success: showResponse,
error: showError
// async:false
};
// 長(zhǎng)輪詢(xún) 和服務(wù)器始終保持一個(gè)連接辛萍。
// 如果當(dāng)前連接請(qǐng)求成功后,將更新數(shù)據(jù)并且繼續(xù)創(chuàng)建一個(gè)新的連接和服務(wù)器保持聯(lián)系羡藐。
// 如果連接超時(shí)或發(fā)生異常贩毕,這個(gè)時(shí)候程序也會(huì)創(chuàng)建一個(gè)新連接繼續(xù)請(qǐng)求。
// 這樣就大大節(jié)省了服務(wù)器和網(wǎng)絡(luò)資源仆嗦,提高了程序的性能辉阶,從而也保證了程序的順序。
(function longPolling(){
form.ajaxSubmit(options);
function showResponse() {
var response_content = JSON.parse(JSON.parse($('#output').html()).response_content);
var data = response_content.now;
console.log('data',response_content,data);
longPolling();
}
function showError() {
var err = $('#output').html();
console.log('err',err);
longPolling();
}
})();
// 模擬表單請(qǐng)求數(shù)據(jù)
$.extend({
StandardPost:function(url,args){
var body = $(document.body),
form = $("<form id='form' method='post'></form>"), // enctype='multipart/form-data'
input;
form.attr({"action":url});
$.each(args,function(key,value){
input = $("<input type='hidden'>");
input.attr({"name":key});
input.val(value);
form.append(input);
});
form.appendTo(document.body);
document.body.removeChild(form[0]);
return form;
}
});
})
原生XHR
// 模擬長(zhǎng)連接ajax
function createStreamingClient(form,progress,succ,err){
var xhr = createXHR(),
received = 0,
type = form.getAttribute('method'),
url = form.getAttribute('action'),
data = serialize(form);
xhr.open(type,url,true);
xhr.onreadystatechange = function(){
var result;
if(xhr.readyState == 3){ // 請(qǐng)求處理中
// 取得最新數(shù)據(jù),并調(diào)整計(jì)數(shù)器
result = xhr.responseText.substring(received);
received += result.length;
// 通過(guò) progress 傳入新的數(shù)據(jù)
progress(result);
}else if(xhr.readyState == 4){
// 請(qǐng)求已完成睛藻,且響應(yīng)已就緒
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
succ && succ(xhr.responseText);
}else{
err && err(xhr.status);
}
createStreamingClient(form,progress,succ,err);
}
}
xhr.send(data);
return xhr;
}
var form = StandardForm('http://106.14.6.153:8888/','POST',{
product_code: 'SIZ7',
type: '1'
});
var client = createStreamingClient(form,function(res){
var result = JSON.parse(res);
console.log('~~~~~~請(qǐng)求處理中~~~~~~',result);
},function(data){
var result = JSON.parse(data);
console.log('~~~~~~請(qǐng)求完成并成功~~~~~~',result);
},function(err){
console.log('~~~~~~請(qǐng)求完成并失敗~~~~~~',err);
});
// ajax-submit
function submitData(form){
var xhr = createXHR();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
console.log('success',result);
}else{
console.log('error',xhr.status);
}
}
}
url = form.getAttribute('action');
type = form.getAttribute('method');
xhr.open(type,url,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(serialize(form));
}
// 模擬form表單
function StandardForm(url,type,args){
var body = document.body,
form = document.createElement('form'), // enctype='multipart/form-data'
input;
form.setAttribute('action',url);
form.setAttribute('method',type);
for(var key in args){
input = document.createElement('input');
input.setAttribute('type','hidden');
input.setAttribute('name',key);
input.setAttribute('value',args[key]);
form.appendChild(input);
}
document.body.appendChild(form)
document.body.removeChild(form);
return form;
}
// 表單序列化
function serialize(form){
var parts = [],
field = null,
i,len,j,optLen,option,optValue;
for(i = 0, len = form.elements.length; i < len; i++){
field = form.elements[i];
switch(field.type){
case 'select-one':
case 'select-multiple':
if(field.name.length){
for(j = 0 ,optLen = field.options.length; j < optLen; j++){
option = field.options[j];
if(option.selected){
optValue = '';
if(option.hasAttrbute){
optValue = (option.hasAttrbute('value') ? option.value : option.text);
}else{
optValue = (option.attributes['value'].specified ? option.value : option.text);
}
parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(optValue));
}
}
}
break;
case undefined: // 字符集
case 'file': //文件輸入
case 'submit': //提交按鈕
case 'reset': //重置按鈕
case 'button': //自定義按鈕
break;
case 'radio': //單選按鈕
case 'checkbox': // 復(fù)選框
if(!field.checked){
break;
}
// 執(zhí)行默認(rèn)操作
default:
if(field.name.length){
parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
}
}
}
return parts.join('&');
}
// 創(chuàng)建XHR對(duì)象
function createXHR(){
if(typeof XMLHttpRequest != 'undefined'){
return new XMLHttpRequest();
}else if(typeof ActiveXObject != 'undefined'){
if(typeof arguments.callee.activeXString != 'string'){
var version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", " MSXML2.XMLHttp"],
i,len;
for(i = 0,len = version.length; i<len; i++){
try{
new ActiveXObject(version[i]);
arguments.callee.activeXString = version[i];
break;
} catch (ex) {
// 跳過(guò)
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error('No XHR object available.');
}
}