ajax 长轮询

长轮询

  • 和服务器始终保持一个连接。
  • 如果当前连接请求成功后,将更新数据并且继续创建一个新的连接和服务器保持联系。
  • 如果连接超时或发生异常,这个时候程序也会创建一个新连接继续请求。

这样就大大节省了服务器和网络资源,提高了程序的性能,从而也保证了程序的顺序。

jquery 写法

$(function(){
     // 这里模拟form表单方式请求数据,因为需要需要跨域
    var form = $.StandardPost('http://xxx.14.6.xxx:8888/',{
        product_code: 'CLZ7',
        type: '1'
    }); 
    var options = {
        target: '#output',          //把服务器返回的内容放入id为output的元素中
        success: showResponse,
        error: showError
        // async:false
    };
    // 长轮询 和服务器始终保持一个连接。
    // 如果当前连接请求成功后,将更新数据并且继续创建一个新的连接和服务器保持联系。
    // 如果连接超时或发生异常,这个时候程序也会创建一个新连接继续请求。
    // 这样就大大节省了服务器和网络资源,提高了程序的性能,从而也保证了程序的顺序。
    (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();
        }
    })();
    // 模拟表单请求数据
    $.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

// 模拟长连接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){  // 请求处理中
            // 取得最新数据,并调整计数器
            result = xhr.responseText.substring(received);
            received += result.length;
            // 通过 progress  传入新的数据 
            progress(result);
        }else if(xhr.readyState == 4){
            // 请求已完成,且响应已就绪
            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('~~~~~~请求处理中~~~~~~',result);
},function(data){
    var result = JSON.parse(data);
    console.log('~~~~~~请求完成并成功~~~~~~',result);
},function(err){
    console.log('~~~~~~请求完成并失败~~~~~~',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': // 复选框
                if(!field.checked){
                    break;
                }
                // 执行默认操作
            default:
                if(field.name.length){
                    parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
                }
        }
    }
    return parts.join('&');
}
// 创建XHR对象
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) {
                    // 跳过
                }
            }
        }
        return new ActiveXObject(arguments.callee.activeXString);
    }else{
        throw new Error('No XHR object available.');
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容