尝试检查页面是否存在时出错(函数返回undefined)

时间:2017-02-02 00:05:16

标签: javascript

我正在尝试检查网址是否存在。如果网址不是404,则该函数返回true,如果是404,则返回false。

现在由于某种原因,此功能正在返回" undefined"

这是我的代码:

function checkURL(url){
    var xmlhttp; // initialize the request object
    // All the browsers except for the old IE
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //old IE
    }
    if (xmlhttp) {
        xmlhttp.open("HEAD", url, true);
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status!=404) {
                return true;
            } else {
                return false;
            }
        }
        xmlhttp.send(null);
    }
}

提前致谢。欢呼声。

1 个答案:

答案 0 :(得分:1)

在AJAX请求完成之前,checkURL的返回值将是未定义的。我会用这样的回调来解决这个问题:

function checkURL(url, cb) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        cb(true)
      } else {
        cb(false)
      }
    };

    request.onerror = function() {
      cb(false)
    };

    request.send();
}


checkURL('https://www.reddit.com/r/javascript.json', function(status) {
    if (status) {
        // did not 404
    } else {
        // 404 or error
    }
})