检查地址路径是否可用

时间:2016-01-15 01:39:07

标签: javascript jquery html

抱歉,这可能是重复的帖子。是否有一种方法可以javascript / jquery来检测url链接是否可用?例如,如果http://www.thisissample.com/可用并且返回true,则检测https://www.google.com.my/不可用并返回false。

2 个答案:

答案 0 :(得分:2)

因此,如果由于跨域限制而发出ajax请求可能会遇到问题,另一种策略是尝试将url加载到脚本标记中,该脚本标记接受其他域。以下是您的代码的样子:

function checkURL(url) { 
    var scriptTag = document.body.appendChild(document.createElement("script"));
    scriptTag.onload = function() {
        alert( url + " is available");
    };
    scriptTag.onerror = function() {
        alert( url + " is not available");
    };
    scriptTag.src = url;
} 

答案 1 :(得分:0)

您可以使用XHR并查看它是否响应404 Not Found。有关HTTP状态代码,请阅读this

请尝试以下代码:

<script>
    function checkURL(url){
        var reader = new XMLHttpRequest();
        var checkFor = url;
        reader.open('get', checkFor, true);
        reader.onreadystatechange = checkReadyState;
        function checkReadyState() {
            if (reader.readyState === 4) {
                if ((reader.status == 200) || (reader.status == 0)) {
                    //document.location.href = checkFor;
                    alert("Page exist !!!");
                }
                else if(request.status === 404) {  
                    alert("Not Found");
                }
                else {
                    alert("Status Code : " + reader.status);
                }

            }
        }
        reader.send(null);
    }
</script>
<body onload="checkURL('http://www.mozill.org/');">
</body>

请注意,它仅适用于相同来源。对于其他主机,您可以使用服务器端语言来执行此操作。如下所示:

<?php
    $url = parse_url('https://www.mozilla.org/');

    $host = $url['host'];
    $port = 80;
    $path = $url['path'];
    $query = (!empty($url['query'])?$url['query']:null);

    $request = "HEAD $path?$query HTTP/1.1\r\n"
              ."Host: $host\r\n"
              ."Connection: close\r\n"
              ."\r\n";

    $address = gethostbyname($host);
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($socket, $address, $port);
    socket_write($socket, $request, strlen($request));
    $response = split(' ', socket_read($socket, 1024));

    if($response[1] >= 200 && $response[1] < 300){
        print "<p>Response: ".$response[1]." - Success URL exist !!!</p>\r\n";
    }
    else if($response[1] >= 300 && $response[1] < 400){
        print "<p>Response: ".$response[1]." - Redirection</p>\r\n";
    }
    else if($response[1] >= 400 && $response[1] < 500){
        print "<p>Response: ".$response[1]." - Client Error</p>\r\n";
    }
    else if($response[1] >= 500){
        print "<p>Response: ".$response[1]." - Server Error</p>\r\n";
    }
    socket_close($socket);
?>

希望这可以帮助你...