XMLHttpRequest status 保持返回 0

XMLHttpRequest status keep return 0

本文关键字:返回 status XMLHttpRequest      更新时间:2023-09-26

>我可以知道我的代码出了什么问题吗? 无论 URL 链接是否可用,它都会返回我 0。

<Script>
  function doSomethingIfFound(url, status) {
    alert(url + " was found, status " + status);
  }
  function doSomethingIfNotFound(url, status) {
    alert(url + " was not found, status " + status);
  }
  function test(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        doSomethingIfFound(url, xhttp.status);
      } else if (xhttp.readyState == 4 && xhttp.status != 200) {
        doSomethingIfNotFound(url, xhttp.status);
      }
    };
    xhttp.open("GET", url, true);
    xhttp.send();
  }
  test("https://test.e-cover.com.my/");
  test("https://www.e-cover.com.my/");
  test("http://www.mypolicy.com.my/mypolicy/login.jsp/");
  test("https://itdidnotexistwhenitrieitiswear.museum/");
</script>

对于前两个网址:

https://www.e-cover.com.my
https://test.e-cover.com.my

我在火虫中收到此错误:跨源请求被阻止:同源策略不允许在 url 上读取远程资源。(原因:缺少 CORS 标头"访问控制-允许源")。这是一篇解释 CORS 的帖子

显然,许多网站都需要这样做,以便来自另一个网站的脚本对其执行http请求。有些网站更宽容,例如:

test("http://www.omdbapi.com/?i=tt1285016");

这工作正常。

另外两个网址:

https://itdidnotexistwhenitrieitiswear.museum
http://www.mypolicy.com.my/mypolicy/login.jsp

只是无法以正常状态打开 200