【问题标题】:Checking if a URL exists or not using javascript [duplicate]使用 javascript 检查 URL 是否存在 [重复]
【发布时间】:2015-06-07 16:37:02
【问题描述】:

我正在尝试检查 URL 是否存在。但我被 CORS 抓住了——这就是我尝试过的:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function checkUrl(url){
        var request = new XMLHttpRequest;
        request.open('GET', url, true);
        request.send();
        request.onreadystatechange = function(){
            if(request.readyState==4){
                if(request.status==200){
                    console.log(request.readyState);
                    return true;
                }
            }else{
                return false;
            }
        }
        };

        var url = 'http://localhost:' + 8080 + '/hello/';
        if(checkUrl(url)){
            alert('Success');
        }else{
            alert('Failure');
        }
    </script>
  </head>
  <body>

  </body>
</html>

我收到错误消息:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/hello/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

注意:我有一个限制:我不能使用任何与 Ajax/jQuery 相关的代码。

请告诉我如何解决这个问题。

【问题讨论】:

  • XMLHttpRequest AJAX。这就是 jQuery 核心 $.ajax 的动力。

标签: javascript


【解决方案1】:

你不能。

浏览器不会让访问的任意网站使用它们来探测其他网站。

您只能使用服务器端代码(您可以使用它通过 Ajax 将信息传递给浏览器)来执行此操作。

【讨论】:

    【解决方案2】:

    您可以从远程站点加载某些内容(例如图像)并使用 onload 处理程序。不能完全证明,但它是你能得到的最好的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-17
      • 2012-12-06
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多