我的onReadyStateChange函数是如何/何时运行的?

时间:2012-11-09 17:14:45

标签: javascript ajax

假设我们有一个从数据库中获取数据的函数:

function getResults() {
    if (httpReq.readyState == 4 || httpReq.readyState == 0) {
        httpReq.open("GET",'../search.php?blablabla',true);
        httpReq.onreadystatechange = function() {
            if (httpReq.readyState == 4) {
                // Some code here
            }
        };
        httpReq.send(null);
    }
    updateResults();
    // This function is running before the code above
    // ...so I actually get no results
}

如果已经从数据库中获取结果,如何运行updateResults()函数?

1 个答案:

答案 0 :(得分:1)

我认为代码应该是这样的:

function getResults() {
    httpReq.open("GET",'../search.php?blablabla',true);
    httpReq.onreadystatechange = function() {
        if (httpReq.readyState == 4) {
            // Some code here
            updateResults();
        }
    };
    httpReq.send(null);
}