0

我正在尝试解决问题XMLHttpRequest,但遇到了一个问题:

function x(url, callback) { //edited

    xmlHttp.onreadystatechange = function() {
        if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) {
            callback(xmlHttp.responseText;) //edited
        } else {
            document.getElementById('content').innerHTML = '<div class="error">Ups, an error ocurred! Server response: <span>'+xmlHttp.responseText+'</span></div>';
        }
    }
    xmlHttp.open('GET', url, true);
    xmlHttp.send(null);
}

function y()
{
    var url = base_url + '?asa=test';
    x(url, function (response) { //edited
       console.log(response);
    });
}

但我的问题是if readyState == 4. 的输出console.log始终是未定义的,永远不会进入if, 只有else,这是因为第一次if执行时,readyState其值为1

所以,任何解决这个问题的方法,因为它让我发疯,我已经尝试了我现在能想到的一切。

更新

代码的格式,这是我最后一次尝试的,因为在我将它分开之前,在变量和我试图解决这个问题的各种事情中

顺便说一句,一个console.log(xmlHttp.readyState)insideonreadystatechange的函数,会一一输出:1、2、3、4

4

1 回答 1

4

正如bergi 所说,请求是异步的。这意味着 x 立即返回,稍后调用 xmlHttp.onreadystatechange 。如果您需要对 y 内部的响应做某事,请将其作为回调传递,以便 x 可以在适当的时候调用它:

function x( callback )
{
    if( pseudocode: request is ok )
    {
        callback( response );
    }
}

function y()
{
    x( url, function( response )
    {
        // do something with the response.
    } );
}

更新

xmlHttp.onreadystatechange 在 4 之前使用 readyState 1、2 和 3 调用。

if( state === 4 )
{
    if( statuscode === 200 )
    {
        // success
    }
    else
    {
        // failure
    }
}
/*else
{
    ignore states 1, 2 and 3
}*/
于 2012-12-02T22:08:30.437 回答