使用XmlHttpRequest控制流程?

时间:2010-02-22 17:52:16

标签: ajax xmlhttprequest control-flow

XmlHttpRequest通过回调工作。那么我怎样才能返回一个值?我试图设置一个全局变量,但这似乎不起作用。

var response = null; // contains the most recent XmlHttpRequest response

// loads the info for this username on the page
function loadUsernameInfo(username) {
    getUserInfo(username);
    var profile = response;
    if (profile) {
        // do stuff
    }
    else {
        indicateInvalidUsername(username);
    }
}
由于回调,

getUserInfo()无法返回结果:

function getUserInfo(username) {
    var request = createRequest();
    request.onreadystatechange = userObjFromJSON;
    var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
    var url = "url.php?url=" + twitterURL;
    request.open("GET", url, true);
    request.send(null);
}

回调:

function userObjFromJSON() {
    if (this.readyState == 4) {
        alert(this.responseText);
        response = this.responseText;
    }
}

如何将回复转回loadUsernameInfo()

1 个答案:

答案 0 :(得分:0)

您可以执行同步请求,但不建议使用 - A用于异步...但正确实现此操作的一般想法是:

var response = null; // contains the most recent XmlHttpRequest response

// loads the info for this username on the page
function loadUsernameInfo(username) {
    getUserInfo(username, onLoadUsernameComplete);
}

function getUserInfo(username, oncomplete) {
    var request = createRequest();
    request.__username = username;
    request.onreadystatechange = oncomplete;
    var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
    var url = "url.php?url=" + twitterURL;
    request.open("GET", url, true);
    request.send(null);
}

function onLoadUsernameComplete(req) {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            var profile = req.responseXML;
            if (profile) {
                // do stuff
            }
            else {
                indicateInvalidUsername(req.__username);
            }
        }
    }
}