不推荐使用主线程上的同步XMLHttpRequest

时间:2016-01-06 10:00:07

标签: javascript ajax multithreading

我在加载文件时在控制台中收到错误:

  

"主线程上的同步XMLHttpRequest因其对最终用户体验的不利影响而被弃用。如需更多帮助,请查看http://xhr.spec.whatwg.org/。"

即使出现错误,数据仍在加载,但需要10到15秒。我想知道正在发生的延迟。

错误源自的代码:

mod.sendRequest=function(type, url, user, pass, data, headers, callback){
    var async=false;
    //check if the last argument is a function and treat it as callback;
    if(arguments[arguments.length-1]  instanceof Function){
        var async=true;
        callback = arguments[arguments.length-1];
    }
    //treat sencond last(if callback)/last(if no callback) argument as headers
    var headindex=arguments.length-((async || arguments[arguments.length-1] == null) ?2:1);
    //is it an array then it's headers
    if(arguments[headindex] instanceof Array){
        headers=arguments[headindex];
    }else{
        headers=[];
    }
    //are user AND password not specified then assume data as 3rd argument.
    if(typeof user == "string" && typeof pass == "string"){
        if(typeof data != "string"){
            data="";
        }
    }else if (typeof user == "string"){
        data = user;
        user=null;
        pass=null;
    }else{
        user=null;
        pass=null;
    }
    var xmlhttp= getHTTP();
    try{
        if(user!=null){
            xmlhttp.open(type, url, async, user, pass);
        }else{
            xmlhttp.open(type, url, async);
        }
    }catch(e){
        throw new mod.RequestOpenFailed(e);
    }
    //set headers
    for(var i=0;i< headers.length;i++){
        try{//opera 8b does not support setRequestHeader todo:
            xmlhttp.setRequestHeader(headers[i][0], headers[i][1]);    
        }catch(e){
        }
    }

    if(async){//set up a callback
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4) {
                callback(xmlhttp);
                xmlhttp = null; //help IE with garbage collection
            }else if (xmlhttp.readyState==2){
                //status property should be available (MS IXMLHTTPRequest documentation) 
                //in Mozilla it is not if the request failed(server not reachable)
                //in IE it is not available at all ?!
                try{//see if it is mozilla otherwise don't care.
                    var isNetscape = netscape;
                    try{//if status is not available the request failed.
                        var s=xmlhttp.status;
                    }catch(e){//call the callback because Mozilla will not get to readystate 4
                        callback(xmlhttp);
                        xmlhttp = null;
                    }
                }catch(e){

                }
            }
        }
    }

    try{
        xmlhttp.send(data);
    }catch(e){            
        if(async){
            callback(xmlhttp, e);
            xmlhttp=null;
        }else{
            throw new mod.SendFailed(e);
        }
    }
    return xmlhttp;
}

0 个答案:

没有答案