javascript - 如何检测ajax错误是Access-Control-Allow-Origin还是文件确实丢失

标签 javascript jquery ajax

我的问题不是关于如何解决 Access-Control-Allow-Origin 问题。执行请求时有时会发生此错误,有时 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
    }
});

查看控制台很容易看出文件是否确实丢失,或者是否是访问控制问题。但我想向用户打印出两条不同的消息,准确说明问题所在。查看报错的变量:function(request, status, message) 它们没有变化,这两种情况都会导致404错误。是否有其他人可以这样做,以便我可以知道问题出在哪里?

预先感谢您的关注。

最佳答案

你的浏览器控制台显示你

XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite.com' is therefore not allowed access.

但是您不能单独使用 JavaScript 访问这些信息。当浏览器检测到 CORS 违规时,它将 discard the header information作为协议(protocol)问题。


一种可行的解决方案是使用服务器端代码检查响应 header 并将结果传回您的客户端页面。例如,如果 ajax 请求失败,您可以调用此脚本(我们称之为 cors.php)并确定它是否包含“Access-Control-Allow-Origin”。

例子:

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

返回

Access-Control-Allow-Origin: *
None

因此,您可以在 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 */

关于javascript - 如何检测ajax错误是Access-Control-Allow-Origin还是文件确实丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22949870/

相关文章:

javascript - HTML 输入显示不随 javascript 改变

javascript - 使用 Trello API 的 client.js 库

javascript - 显示复选框选定项目的结果

java - Spring MVC - AJAX/JSON - ResponseBody -> 调用服务

javascript - 为什么没有设置全局变量值?

javascript - 带装载机的折叠面板

javascript - 未捕获的类型错误 : Cannot read property '__e3_' of null

javascript - 根据选项卡内的文本链接的哈希 ID 动态选择 jquery UI 选项卡

javascript - 滚动时 JQuery 动画滞后

javascript - 标记<img src =“file://c:/localfile.png”>在服务器上时没有上传图像的权限,如何解决?