Javascript 函数 onload 从未被调用

标签 javascript xmlhttprequest

我希望通过Web服务的get请求获取一个json文件,并且我有一个“跨源请求”,所以我检查“withCredentials”,然后使用onload函数在上显示json的内容控制台。

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();

  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
    console.log("withCredentials is true");

    xhr.onload = function() {
      console.log('ok');
      if (xhr.status >= 200 && xhr.status < 400) {
        data.forEach(card => {
          console.log(card.nameEnglish1);
        })
      } else {
        console.log('error');
      }
    };

    xhr.onerror = function() {
      console.log('There was an error!');
    };

  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

var xhr = createCORSRequest('GET', 'http://192.168.42.176:8080/batch-recup-mtg-0.0.1-SNAPSHOT/mtg/cards/search?setCode=AKH');
if (!xhr) {
  throw new Error('CORS not supported');
}

但是什么也没发生,我的 onload 函数从未被调用,并且我没有任何错误。我确信网络服务正在工作,因为我在浏览器中尝试过它。您知道为什么 onload 函数从未被调用吗?

编辑:显示 console.log("withCredentials is true");,但不显示 console.log('ok');

最佳答案

你需要

xhr.send();

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();

  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
    console.log("withCredentials is true");

    xhr.onload = function() {
      console.log('ok');
      if (xhr.status >= 200 && xhr.status < 400) {
        data.forEach(card => {
          console.log(card.nameEnglish1);
        })
      } else {
        console.log('error');
      }
    };

    xhr.onerror = function() {
      console.log('There was an error!');
    };

    // added send call here:
    xhr.send();

  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

var xhr = createCORSRequest('GET', 'http://google.com/');
if (!xhr) {
  throw new Error('CORS not supported');
}

关于Javascript 函数 onload 从未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55599552/

相关文章:

php - 避免 CORS 在 codeigniter 中不起作用

javascript - 使用 blueimp jQuery 文件上传

javascript - 根据总成本的百分比计算成本

javascript - react 连接到 Node Cors 预检失败

javascript - 简单的 ajax 调用似乎被阻塞

javascript - 将图像从移动网络应用程序(PhoneGap 和 JavaScript)上传到 SOAP 网络服务返回状态 0

javascript - XHR 0x80004005 (NS_ERROR_FAILURE) 具有非常简单的 HTTP 请求

javascript - 在 javascript 中收听网页上的传出请求

javascript - 分配给变量时如何将方法绑定(bind)到原始上下文

javascript - AngularJS:未捕获错误:[$injector:nomod] 模块 _ 不可用! |对模块的多次引用