CORS在某些情况下会失败,但在其他情况下却不会

时间:2019-07-25 15:50:25

标签: javascript cors

我在服务器中配置了正确的CORS标头。 当我尝试执行此操作时会起作用:

function loadDoc() {
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };
  xhttp.open("GET", "http://myurl.com/some/path", true);
  xhttp.send();
}

但是当我这样做时失败了:

function loadDoc() {
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "http://myurl.com/some/path", true);
  xhttp.send();
}

如您所见,唯一的区别是在第二个代码块中,我使用响应文本并将其放入html元素中。

编辑:

这是我在第二种情况下遇到的错误:

Access to XMLHttpRequest at 'http://myurl.com/some/path' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1 个答案:

答案 0 :(得分:-1)

document.getElementById()很可能会失败,因为DOM还没有准备好。在访问DOM之前,有几种方法可以确保它们准备就绪。无论使用哪种浏览器代理,实现此目标的最可靠方法是使用jQuery的ready()方法,如下所示:

$(document).ready(function () {
    // access DOM here
});

我们中的某些人仅将jQuery库用于此目的。 :)。 但是,还有其他方法可以实现此目的。参见this post

相关问题