有网页要调用多个页面的内容,但我想只实例化一个xmlhttp,一个一个的访问需要调用的网页(即status==200后 open下一个网页),我按这个思路写了段代码试验,没有起作用,请问有没有办法实现只用一个xmlhttp呢?代码如下:var xmlhttp=null;
function GetColor(){
if(window.ActiveXObject) xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
else if(window.window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=HandleStateChange;
xmlhttp.open("POST","resp.php",true);
xmlhttp.send(null);
}
function HandleStateChange(){
if (xmlhttp.readyState==4){
xmlhttp.onreadystatechange=HandleStateChange2;
xmlhttp.open("POST","resp.php",true);  //再打开一次resp.php,这次等待时将显示loading2... 不过没有实现
xmlhttp.send(null);
}
else document.getElementById('text').value='loading...';
}
function HandleStateChange2(){
if (xmlhttp.readyState==4){
document.getElementById('text').value='ok2';
}
else document.getElementById('text').value='loading2...';
}

解决方案 »

  1.   


    <input id="text" /><script>
    // ajax(url, data, onComplete, onStart, onFail, method)
    var ajax = function() {
    var pendingTransactions = []; // 待处理事务队列. 不是什么序列化, 就是说,排队,一个一个来,未轮到的,先放在数组里
    var working = false;
    var xhr = function() {
    try {
    return new XMLHttpRequest();
    } catch(e) { try {
    return new ActiveXObject("MSXML2.XMLHTTP");
    } catch(e) { try {
    return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
    return false;
    } } }
    }();
    function ajax(url, data, onComplete, onStart, onFail, method) {
    pendingTransactions.push({
    url:url
    , data:data
    , onComplete:onComplete
    , onFail:onFail
    , method:method
    , onStart:onStart
    });
    ajaxStart();
    };
    function reStart() {
    ajaxStart(true);
    }
    function empty() { }
    function ajaxStart(ignoreWorkingFlag) {
    if (working && !ignoreWorkingFlag) return;
    if (pendingTransactions.length < 1) return working = false;
    working = true;
    var trans = pendingTransactions.shift();
    xhr.open(trans.method||"POST", trans.url, true);
    xhr.onreadystatechange = function() {
    if (xhr.readyState != 4) return;
    var next = xhr.status == 200 ? trans.onComplete : trans.onFail;
    next = next || empty;
    if (next.length > 1) {
    next(xhr, reStart);
    } else {
    next(xhr);
    reStart();
    }
    };
    (trans.onStart || empty)();
    xhr.send(trans.data);
    }
    return ajax;
    }();
    // 第一次
    ajax("resp.php", null, function(xhr) {
    // onComplete
    // ...
    }, function() {
    // onStart
    document.getElementById('text').value='loading...'
    });
    // 第二次
    ajax("resp.php", null, function(xhr) {
    // onComplete
            document.getElementById('text').value = 'ok2';
    }, function() {
    // onStart
    document.getElementById('text').value='loading2...';
    });</script>
      

  2.   

    不能再次使用,再次使用必须先执行open