if-URL-exists使用javascript检查

时间:2014-03-10 05:14:49

标签: javascript http-status-code-404

我正在尝试在URL上创建if-file-exists检查。

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else xhr = null;
  return xhr;
}

function UrlExists(url) {
  var http = createCORSRequest('HEAD', url);
  http.onreadystatechange = function() {
    if (this.readyState == this.DONE) {
      if (this.status == 404) {
        alert(url + " is NOT available!");
      } else if (this.status != 0) {
        alert(url + " is available!");
      }
    }
  };
  http.send();
}

UrlExists("http://bar.baz");
UrlExists("http://google.com");
</script>
Testing URLs
</body>
</html>

目前收到XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.错误 - 即使它在Mac OS 10.9上运行Apache HTTPd。

你们能帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

这是一个跨领域问题。 你必须使用代理。 例如,我使用过YQL。 请尝试以下方法:

function isValidURL(url) {
    var encodedURL = encodeURIComponent(url);
    var isValid = false;

    $.ajax({
      url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
      type: "get",
      async: false,
      dataType: "json",
      success: function(data) {
        isValid = data.query.results != null;
      },
      error: function(){
        isValid = false;
      }
    });

    return isValid;
}

用法很简单:

var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");