XMLHttpRequest()在函数中返回响应


XMLHttpRequest() returning response in a function

我有一个函数isOnline(),它看起来像这样:

function isOnline() {
    var request=new XMLHttpRequest(); 
    request.onreadystatechange=function() {
        if(request.readyState==4) {
            if(request.responseText=="online")
                return true;    
        }    
    }
    request.open("GET","onlinecheck.php?user=user",false);
    request.send();
    return false;
}

如果我运行document.write(isOnline());进行测试,我总是得到false,(未定义如果我不写return false;,我得到未定义。

如何在readyState为4之前"等待",然后返回true?

您需要关注以下几点:

  • onreadystatechange在发送异步请求时使用-更多信息请参阅此处
  • 因此,如果您正在尝试发送异步请求,请在调用中使用async=true-在此处阅读更多信息。

    request.open("GET", "onlinecheck.php?user=user", true);
    
  • 最后,如果要使用异步调用,则不能返回值。检查这两个链接

    1. 从AJAX中的事件onreadystatechange返回值
    2. 如何从异步回调函数返回值

如果您决定同步执行:

function isOnline() {
    var request=new XMLHttpRequest(); 
    request.open("GET","www.google.com/",false);
    request.send();
    /* check the readyState, you can also check for status code */
    if (request.readyState === 4)
        // put other conditions here if you need to    
        return true;
    else
        return false;
}
// It returns true