开发者

How do i return value in this example?

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);

}

}



}
}

i have the above code. What is right way to return var resul to nicktoid routine??


Use a callback function, since the Ajax request executes asynchronously

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

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


ajax in general is asynchronous.

So you cannot return -- you must use callbacks.


So you can do nextFuntion(resul); and parse your information there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜