Javascript检查地址路径链接是否可用

时间:2016-01-19 01:57:22

标签: javascript html hyperlink



<script>
  function doSomethingIfFound(url, status) {
    alert(url + " was found, status" + status);
  }

  function doSomethingIfNotFound(url, status) {
    alert(url + " was not found, status" + status);
  }

  function test(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        doSomethingIfFound(url, xhttp.status);
      } else if (xhttp.readyState == 4 && xhttp.status != 200) {
        doSomethingIfNotFound(url, xhttp.status);
      }
    };
    xhttp.open("GET", url, true);
    xhttp.send();
  }


  test('https://test.e-cover.com.my/')
  test('https://www.e-cover.com.my/')
  test('http://www.mypolicy.com.my/mypolicy/login.jsp/')
  test('https://itdidnotexistwhenitrieitiswear.museum/')
</script>
&#13;
&#13;
&#13;

我不知道为什么我的代码会检测到某些网址链接可用而某些网址链接不可用,尽管所谓的&#34;不可用&#34;可用。请帮助,谢谢。

&#13;
&#13;
<script>
  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;
  }
</script>

<body>

  link 1 available site detected as available (correct output) :
  <input type="radio" name="link" onclick="checkURL('https://www.e-cover.com.my/');">
  <br/>link 2 available site but detected as not available :
  <input type="radio" name="link" onclick="checkURL('https://test.e-cover.com.my/');">
  <br/>link 3 available site but detected as not available :
  <input type="radio" name="link" onclick="checkURL('http://www.mypolicy.com.my/mypolicy/login.jsp/');">
  <br/>

</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

这个想法很整洁,但你不能这样做,你需要做得好,对不起。只需执行AJAX请求并忽略返回,只需检查HTTP代码即可。

function doSomethingIfFound(url, status){
  console.log(url + " was found, status" + status);
}
function doSomethingIfNotFound(url, status){
  console.log(url + " was not found, status" + status);
}
function test(url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      doSomethingIfFound(url, xhttp.status);
    } else if ( xhttp.readyState == 4 && xhttp.status != 200 ){
      doSomethingIfNotFound(url, xhttp.status);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}


test("https://test.e-cover.com.my/")
test("https://www.e-cover.com.my/")
test("http://www.mypolicy.com.my/mypolicy/login.jsp/")
test("https://itdidnotexistwhenitrieitiswear.museum/")

给出结果

&#34; https://test.e-cover.com.my/被发现,状态200&#34;
&#34; https://itdidnotexistwhenitrieitiswear.museum/未找到,状态0&#34;
&#34; https://www.e-cover.com.my/被发现,状态200&#34;
&#34; http://www.mypolicy.com.my/mypolicy/login.jsp/未找到,状态404&#34;

因此,如果网址根本不存在,请求会返回0404如果网站存在,但没有您想要的网页,200如果一切正常,适当的。

如果仍然不适合你,你需要在细节上更精确。