Javascript 如何检测ajax错误是访问控制允许源还是文件确实丢失

Javascript 如何检测ajax错误是访问控制允许源还是文件确实丢失,javascript,jquery,ajax,Javascript,Jquery,Ajax,我的问题不是关于如何解决访问控制允许来源问题。执行请求时有时会发生此错误,其他时候url可能已过时。但是我想根据不同的错误为用户打印不同的消息 目前我有以下代码: $.ajax( { url: link, type:'HEAD', timeout: 2000, error: function(request, status, message) { console.log('ajax error'); console.log(

我的问题不是关于如何解决访问控制允许来源问题。执行请求时有时会发生此错误,其他时候url可能已过时。但是我想根据不同的错误为用户打印不同的消息

目前我有以下代码:

$.ajax(
{
    url: link,
    type:'HEAD',
    timeout: 2000,
    error: function(request, status, message)
    {
        console.log('ajax error');
        console.log(request);
        console.log(status);
        console.log(message);
        openPopUp("There was an error accessing the image. It can be because the address is invalid, "+
            "or because the server where the image is stored is not allowing direct access to the images.");
    },
    success: function()
    {
        // More stuff here
    }
});
查看控制台,很容易看出文件是否确实丢失,或者是访问控制问题。但是我想向用户打印两条不同的消息,确切地说明问题所在。查看错误中的变量:函数(请求、状态、消息)它们不会更改,这两种情况都会导致404错误。有没有其他方法可以让我知道问题出在哪里


提前感谢您的关注。

您应该能够从请求对象读取响应标题:

var acao=request.getResponseHeader('Access-Control-Allow-Origin')


然后根据标题是否存在以及url是否在值中,输出相应的错误。

您的浏览器控制台会显示您的错误

无法加载XMLHttpRequesthttp://www.google.com/. 请求的资源上不存在“Access Control Allow Origin”标头。起源'http://mysite.com因此,不允许访问

但是您不能单独使用JavaScript访问这些信息。当浏览器检测到CORS违规时,它将作为协议问题进行处理


一个有效的解决方案是使用服务器端代码检查响应头,并将结果传递回客户端页面。例如,如果ajax请求失败,您可以调用这个脚本(我们称它为
cors.php
),并确定它是否包含“访问控制允许源代码”

例如:

php?url=http://ip.jsontest.com
php?url=http://www.google.com

返回

访问控制允许来源:*
没有

因此,您可以在JavaScript代码中执行以下操作:

$.ajax({
  url: "http://www.google.com",
  timeout: 4000,
  statusCode: {
    404: function() {
      // Simple not found page, but not CORS violation
      console.log(this.url + " not found" );
    }
  }
})
.fail(function(jqXHR, textStatus) {
   // Empty status is a sign that this may be a CORS violation
   // but also check if the request timed out, or that the domain exists
   if(jqXHR.status > 0 || jqXHR.statusText == "timeout") {
      console.log("Failure because: "+jqXHR.status+" "+jqXHR.statusText+" error"); 
      return;
   }

   // Determine if this was a CORS violation or not
   console.log("Checking if this is a CORS violation at - " + this.url);
   $.ajax({
      url: "http://myserver.net/cors.php?url=" + escape(this.url),
   })
   .done(function(msg) {
      // Check for the Access-Control-Allow-Origin header
      if(msg.indexOf("Access-Control-Allow-Origin") >= 0) {
        console.log("Failed bacause '" + msg + "'");
      } else {
        console.log("Failed bacause of CORS violation");
      }
   });
})
.done(function(msg) {
  // Successful ajax request
  console.log(msg);
}); /* Drakes, 2015 */
根据您自己的需要自定义此PHP脚本:

<?php 
/* cors.php */

$url = $_GET["url"];
if(isset($url)) {
    $headers = getHeaders($url, "Access-Control-Allow-Origin");
    header("Access-Control-Allow-Origin: *"); // Allow your own cross-site requests
    echo count($headers) > 0 ? $headers[0] : "None";
}

// Get the response headers, only specific ones
function getHeaders($url, $needle = false) {
    $headers = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // Only get the headers
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header_line) use(&$headers, $needle) {
        if(!$needle || strpos($header_line, $needle) !== false) {
            array_push($headers, $header_line);
        }
        return strlen($header_line);
    });
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_exec($ch); 
    return $headers;
} /* Drakes, 2015 */

这似乎是一个很好的方法,但不幸的是,当问题是访问控制Allow Origin时,我无法访问标题。即使使用getAllResponseHeaders()我也会得到一个空列表。控制台中有什么变化?你能举几个不同案例的例子吗?似乎如果你能看到控制台的不同,它应该在某个地方对你有用…当然。当我试图访问一个已存在但无法访问的映像时,会出现错误:XMLHttpRequest无法加载。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。如果我试图打开一个错误的链接,我会得到:HEAD net::ERR_NAME_NOT_RESOLVED+1,表示“当浏览器检测到CORS冲突时,它将根据协议丢弃标题信息。”。这让我快发疯了。