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

Javascript 我的onReadyStateChange函数如何/何时运行?,javascript,ajax,Javascript,Ajax,假设我们有一个从数据库获取数据的函数: function getResults() { if (httpReq.readyState == 4 || httpReq.readyState == 0) { httpReq.open("GET",'../search.php?blablabla',true); httpReq.onreadystatechange = function() { if (httpReq.readyState

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

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()
函数?

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

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

您必须将updateResults()放入;在“//some code here”处,所有脚本都不正确。看@Gael:为什么“所有的剧本”都不正确?如果我有点残忍,请原谅!httpReq没有定义(或者在函数外部,它不是很干净),在发送请求之前检查readyState(虽然,如果允许它等于0,它会工作)。我编辑了线程,以便您了解我是如何创建请求的。