function nicktoid(nick){
    if (typeof nick == "String") {
    var u = "http://xxxxxx.xxxx/" + nick ;
    var xhr2 = new XMLHttpRequest();
    xhr2.open('GET',u, true);
    xhr2.setRequestHeader('Cache-Control', 'no-cache');
    xhr2.setRequestHeader('Pragma', 'no-cache');

    xhr2.onreadystatechange = function() {
        if (xhr2.readyState == 4)  {
        txt2 = xhr2.responseText;
        var el2 = document.createElement("div");
        el2.innerHTML = txt2;

        anchors = el2.getElementsByTagName("a");
        for (var i=0;i< anchors.length;i++){
            if (anchors[i].parentNode.id == "profile_avatar"){

                anc.push(anchors[i]);
            }


        }

        var res = anc[0].href;
        var arstr = res.split("_");
        var resul = arstr[0].substr(6);

}

}



}
}


我有上面的代码。将var resul返回到nicktoid例程的正确方法是什么?

最佳答案

使用回调函数,因为Ajax请求异步执行

function nicktoid(nick, callback){
    ...
    xhr2.onreadystatechange = function() {
        ...
        callback && callback(resul);
    }
}

nicktoid('foobar', function(resul) {
    console.log(resul);
});

09-17 22:32